]>
Commit | Line | Data |
---|---|---|
6f1a3f9c RD |
1 | #---------------------------------------------------------------------------- |
2 | # Name: objutils.py | |
3 | # Purpose: Object Utilities | |
4 | # | |
5 | # Author: Alan Mullendore | |
6 | # | |
7 | # Created: 5/10/05 | |
8 | # CVS-ID: $Id$ | |
9 | # Copyright: (c) 2004-2005 ActiveGrid, Inc. | |
10 | # License: wxWindows License | |
11 | #---------------------------------------------------------------------------- | |
12 | ||
13 | import logging | |
14 | import traceback | |
15 | import sys | |
16 | import os | |
02b800ce RD |
17 | import __builtin__ |
18 | import types | |
19 | import xml.sax.saxutils as saxutils | |
2eeaec19 | 20 | from types import * |
02b800ce | 21 | from activegrid.util.lang import * |
6f1a3f9c | 22 | |
02b800ce RD |
23 | FUNCTION_HAS_ATTR = '_hasAttr' |
24 | FUNCTION_GET_ATTR = '_getAttr' | |
25 | FUNCTION_SET_ATTR = '_setAttr' | |
26 | FUNCTION_DEL_ATTR = '_delAttr' | |
27 | ||
28 | def hasRawAttr(obj, name): | |
29 | if obj == None: | |
30 | return False | |
31 | if name != FUNCTION_HAS_ATTR and hasattr(obj, FUNCTION_HAS_ATTR): | |
32 | return obj._hasAttr(name) | |
33 | return obj.__dict__.has_key(name) | |
34 | ||
35 | def getRawAttr(obj, name): | |
36 | if name != FUNCTION_GET_ATTR and hasattr(obj, FUNCTION_GET_ATTR): | |
37 | return obj._getAttr(name) | |
38 | return obj.__dict__.get(name) | |
39 | ||
40 | def setRawAttr(obj, name, value): | |
41 | if name != FUNCTION_SET_ATTR and hasattr(obj, FUNCTION_SET_ATTR): | |
42 | obj._setAttr(name, value) | |
43 | else: | |
44 | obj.__dict__[name] = value | |
45 | ||
46 | def delRawAttr(obj, name): | |
47 | if name != FUNCTION_DEL_ATTR and hasattr(obj, FUNCTION_DEL_ATTR): | |
48 | obj._delAttr(name) | |
49 | else: | |
50 | del obj.__dict__[name] | |
51 | ||
52 | def getStaticAttr(obj, attr): | |
53 | if (isinstance(obj, types.TypeType)): | |
54 | classDesc = obj | |
55 | else: | |
56 | classDesc = obj.__class__ | |
57 | if (hasattr(classDesc, attr)): | |
58 | return getattr(classDesc, attr) | |
59 | return None | |
60 | ||
61 | def setStaticAttr(obj, attr, value): | |
62 | if (isinstance(obj, types.TypeType)): | |
63 | classDesc = obj | |
64 | else: | |
65 | classDesc = obj.__class__ | |
66 | setattr(classDesc, attr, value) | |
67 | ||
68 | def moduleForName(moduleName): | |
69 | module = None | |
70 | pathList = moduleName.split('.') | |
71 | if (len(moduleName) > 0): | |
72 | module = __import__(moduleName) | |
73 | for name in pathList[1:]: | |
74 | if (name in module.__dict__): | |
75 | module = module.__dict__[name] | |
76 | else: | |
77 | module = None | |
78 | break | |
79 | return module | |
80 | ||
81 | def typeForName(typeName): | |
82 | i = typeName.rfind('.') | |
83 | if (i >= 0): | |
84 | module = moduleForName(typeName[:i]) | |
85 | if (module != None): | |
86 | name = typeName[i+1:] | |
87 | if (name in module.__dict__): | |
88 | return module.__dict__[name] | |
89 | elif __builtin__.__dict__.has_key(typeName): | |
90 | return __builtin__.__dict__[typeName] | |
91 | return None | |
92 | ||
93 | def functionForName(functionName): | |
94 | ftype = typeForName(functionName) | |
95 | if (isinstance(ftype, (types.FunctionType, types.MethodType, types.BuiltinFunctionType, types.BuiltinMethodType))): | |
96 | return ftype | |
97 | return None | |
98 | ||
6f1a3f9c | 99 | def classForName(className): |
02b800ce RD |
100 | ctype = typeForName(className) |
101 | if (isinstance(ctype, (types.ClassType, types.TypeType))): | |
102 | return ctype | |
103 | return None | |
6f1a3f9c | 104 | |
02b800ce RD |
105 | def newInstance(className, objargs=None): |
106 | "dynamically create an object based on the className and return it." | |
26ee3a06 | 107 | |
02b800ce RD |
108 | if not isinstance(objargs, list): |
109 | objargs = [objargs] | |
110 | ||
111 | if className == "None": | |
112 | return None | |
113 | elif className == "bool": | |
114 | if ((len(objargs) < 1) or (objargs[0].lower() == "false") or (not objargs[0])): | |
115 | return False | |
116 | return True | |
117 | if className == "str" or className == "unicode": # don"t strip: blanks are significant | |
118 | if len(objargs) > 0: | |
119 | try: | |
120 | return saxutils.unescape(objargs[0]).encode() | |
121 | except: | |
122 | return "?" | |
123 | else: | |
124 | return "" | |
125 | ||
126 | classtype = classForName(className) | |
127 | if (classtype == None): | |
128 | raise Exception("Could not find class %s" % className) | |
129 | ||
130 | if (len(objargs) > 0): | |
131 | return classtype(*objargs) | |
132 | else: | |
133 | return classtype() | |
134 | ||
135 | def getClassProperty(classType, propertyName): | |
136 | return getattr(classType, propertyName) | |
137 | ||
138 | def toDiffableRepr(value, exclude=None): | |
139 | if (value == None): | |
140 | return "None" | |
141 | ## elif (isinstance(value, ObjectType) and hasattr(value, "__dict__")): | |
142 | ## if (exclude == None): | |
143 | ## exclude = [] | |
144 | ## s = "%s(%s)" % (type(value), toDiffableString(value.__dict__, exclude)) | |
145 | elif (not isinstance(value, (BooleanType, ClassType, ComplexType, DictType, DictionaryType, | |
146 | FloatType, IntType, ListType, LongType, StringType, TupleType, | |
147 | UnicodeType, BufferType, BuiltinFunctionType, BuiltinMethodType, | |
148 | CodeType, FrameType, FunctionType, GeneratorType, InstanceType, | |
149 | LambdaType, MethodType, ModuleType, SliceType, TracebackType, | |
150 | TypeType, XRangeType))): | |
151 | if (hasattr(value, "__str__")): | |
152 | s = str(value) | |
153 | elif (hasattr(value, "__dict__")): | |
154 | s = "%s(%s)" % (type(value), toDiffableString(value.__dict__, exclude)) | |
155 | else: | |
156 | s = str(type(value)) | |
157 | ix2 = s.find(" object at 0x") | |
158 | if (ix2 > 0): | |
159 | ix = s.rfind(".") | |
160 | if (ix > 0): | |
161 | s = "<class %s>" %s[ix+1:ix2] | |
162 | elif (isinstance(value, bool)): | |
163 | if (value): | |
164 | return "True" | |
165 | else: | |
166 | return "False" | |
167 | elif (isinstance(value, (tuple, list))): | |
168 | items = [] | |
169 | for v in value: | |
170 | if (isinstance(v, basestring)): | |
171 | if (v.find("'") >= 0): | |
172 | items.append('"%s"' % v) | |
173 | else: | |
174 | items.append("'%s'" % v) | |
175 | else: | |
176 | items.append(toDiffableString(v, exclude)) | |
177 | s = "[" + ", ".join(items) + "]" | |
178 | elif (isinstance(value, dict)): | |
179 | if (exclude == None): | |
180 | exclude = [] | |
181 | items = [] | |
182 | for key, val in value.iteritems(): | |
183 | if (isinstance(val, UnicodeType)): | |
184 | items.append("'%s': u'%s'" % (key, toDiffableString(val, exclude))) | |
185 | elif (isinstance(val, basestring)): | |
186 | items.append("'%s': '%s'" % (key, toDiffableString(val, exclude))) | |
187 | else: | |
188 | items.append("'%s': %s" % (key, toDiffableString(val, exclude))) | |
189 | s = "{" + ", ".join(items) + "}" | |
190 | else: | |
191 | s = str(value) | |
192 | return s | |
193 | ||
194 | def toDiffableString(value, exclude=None): | |
195 | if (value == None): | |
196 | return "None" | |
197 | if ((exclude != None) and not isinstance(value, (basestring, int))): | |
198 | for v in exclude: | |
199 | if (v is value): | |
200 | return "<recursive reference>" | |
201 | exclude.append(value) | |
202 | s = toDiffableRepr(value) | |
26ee3a06 RD |
203 | ds = "" |
204 | i = s.find(" at 0x") | |
205 | start = 0 | |
206 | while (i >= 0): | |
207 | j = s.find(">", i) | |
208 | if (j < i): | |
209 | break | |
210 | ds += s[start:i] | |
211 | start = j | |
212 | i = s.find(" at 0x", start) | |
02b800ce RD |
213 | ds = ds + s[start:] |
214 | i = ds.find("\\src\\") | |
215 | if (i < 0): | |
216 | i = ds.find("/src/") | |
217 | else: | |
218 | ds = ds.replace("\\", "/") | |
219 | if (i > 0): | |
220 | i += 4 | |
221 | if (ds[i:i+5] == "\\php\\"): | |
222 | i += 4 | |
223 | elif (ds[i:i+8] == "\\python\\"): | |
224 | i += 7 | |
225 | ds = "filepath: ..." + ds[i:] | |
226 | return ds | |
227 | ||
2eeaec19 RD |
228 | def toString(value, options=0): |
229 | if ((options & PRINT_OBJ_DIFFABLE) > 0): | |
230 | return toDiffableString(value) | |
02b800ce RD |
231 | elif (not isinstance(value, basestring)): |
232 | return str(value) | |
2eeaec19 RD |
233 | return value |
234 | ||
02b800ce | 235 | def typeToString(obj, options=0): |
2eeaec19 RD |
236 | if (isinstance(obj, BooleanType)): |
237 | return "bool" | |
238 | elif (isinstance(obj, UnicodeType)): | |
02b800ce RD |
239 | if ((options & PRINT_OBJ_DIFFABLE) > 0): |
240 | return "string" | |
2eeaec19 RD |
241 | return "unicode" |
242 | elif (isinstance(obj, basestring)): | |
243 | return "string" | |
244 | elif (isinstance(obj, IntType)): | |
245 | return "int" | |
02b800ce RD |
246 | elif (isinstance(obj, LongType)): |
247 | if ((options & PRINT_OBJ_DIFFABLE) > 0): | |
248 | return "int" | |
249 | return "long" | |
2eeaec19 RD |
250 | elif (isinstance(obj, FloatType)): |
251 | return "float" | |
252 | elif (type(obj) == ListType): | |
253 | return "list" | |
254 | elif (isinstance(obj, DictType)): | |
255 | return "dict" | |
256 | elif (isinstance(obj, TupleType)): | |
257 | return "tuple" | |
258 | elif (isinstance(obj, InstanceType)): | |
02b800ce RD |
259 | ## ds = str(type(obj)) |
260 | ds = "<class %s.%s> " % (obj.__module__, obj.__class__.__name__) | |
2eeaec19 | 261 | else: |
02b800ce RD |
262 | ds = str(type(obj)) |
263 | if (options == 0): | |
264 | import activegrid.util.aglogging | |
265 | options = activegrid.util.aglogging.testMode(0, PRINT_OBJ_DIFFABLE) | |
266 | if ((options & PRINT_OBJ_DIFFABLE) > 0): | |
267 | if (ds.startswith("<class ")): | |
268 | ix = ds.rfind(".") | |
269 | if (ix < 0): | |
270 | ix = 8 | |
271 | ds = "<class %s>" % ds[ix+1:-2] | |
272 | return ds | |
273 | ||
274 | def nameToString(name, options=0): | |
275 | if (name.startswith("_v_")): | |
276 | return name[3:] | |
277 | if ((options & PRINT_OBJ_DIFFABLE) > 0): | |
278 | ix = name.find("__") | |
279 | if ((ix > 1) and name.startswith("_")): | |
280 | name = name[ix:] | |
281 | return toDiffableString(name) | |
282 | return name | |
2eeaec19 | 283 | |
26ee3a06 RD |
284 | PRINT_OBJ_GETATTR = 1 |
285 | PRINT_OBJ_HIDE_INTERNAL = 2 | |
286 | PRINT_OBJ_COMPACT = 4 | |
287 | PRINT_OBJ_NONONE = 8 | |
2eeaec19 | 288 | PRINT_OBJ_DIFFABLE = 16 |
02b800ce | 289 | PRINT_OBJ_HIDE_EXCLUDED = 32 |
26ee3a06 RD |
290 | PRINT_OBJ_INTERNAL = 512 |
291 | ||
02b800ce RD |
292 | def printObject(out, object, name=None, indent=0, flags=0, exclude=None, remove=None, maxIndent=30): |
293 | if (name == None): | |
294 | name = "" | |
295 | ## elif (name.endswith("_") and not name.endswith("__")): | |
296 | ## name = name[:-1] | |
297 | if ((remove != None) and (name in asDict(remove))): | |
298 | return False | |
26ee3a06 | 299 | if ((maxIndent != None) and (indent > maxIndent)): |
2eeaec19 RD |
300 | print >> out, " "*indent, "%s: %s" % (name, toString(str(object), flags)), |
301 | if ((flags & PRINT_OBJ_INTERNAL) == 0): | |
302 | print >> out | |
26ee3a06 RD |
303 | return True |
304 | finalNewLine = False | |
305 | printed = True | |
02b800ce RD |
306 | if ((flags & (PRINT_OBJ_COMPACT | PRINT_OBJ_HIDE_EXCLUDED)) > 0): |
307 | if ((exclude != None) and ((object in exclude) or (name in exclude))): | |
26ee3a06 | 308 | return |
02b800ce RD |
309 | if ((flags & PRINT_OBJ_COMPACT) > 0): |
310 | indent = 0 | |
26ee3a06 RD |
311 | if ((flags & PRINT_OBJ_INTERNAL) == 0): |
312 | finalNewLine = True | |
313 | flags |= PRINT_OBJ_INTERNAL | |
2eeaec19 | 314 | if (object is None): |
26ee3a06 RD |
315 | if (flags & PRINT_OBJ_NONONE) == 0: |
316 | print >> out, " "*indent, name, " = None", | |
317 | else: | |
318 | finalNewLine = False | |
319 | printed = False | |
02b800ce | 320 | elif (name.startswith("_") and ((flags & PRINT_OBJ_HIDE_INTERNAL) > 0) and not name.startswith("_v_")): |
26ee3a06 RD |
321 | finalNewLine = False |
322 | printed = False | |
323 | elif (isinstance(object, (list, tuple))): | |
2eeaec19 | 324 | if ((exclude != None) and object in exclude): |
02b800ce | 325 | print >> out, " "*indent, name, " : ", typeToString(object, flags), " of length = ", len(object), " (already printed)", |
2eeaec19 | 326 | elif ((exclude != None) and name in exclude): |
02b800ce | 327 | print >> out, " "*indent, name, " : ", typeToString(object, flags), " of length = ", len(object), " (excluded)", |
26ee3a06 | 328 | else: |
2eeaec19 | 329 | if ((exclude != None) and (len(object) > 0)): exclude.append(object) |
02b800ce | 330 | print >> out, " "*indent, name, " : ", typeToString(object, flags), " of length = %d" % len(object), |
26ee3a06 RD |
331 | for i, o in enumerate(object): |
332 | print >> out | |
02b800ce | 333 | printObject(out, o, name="[%d]" % i, indent=indent+2, flags=flags, exclude=exclude, remove=remove, maxIndent=maxIndent) |
26ee3a06 | 334 | elif (isinstance(object, dict)): |
2eeaec19 | 335 | if ((exclude != None) and object in exclude): |
02b800ce | 336 | print >> out, " "*indent, name, " : ", typeToString(object, flags), " (already printed)", |
26ee3a06 | 337 | else: |
2eeaec19 | 338 | if ((exclude != None) and (len(object) > 0)): exclude.append(object) |
26ee3a06 RD |
339 | if (len(name) > 0): |
340 | print >> out, " "*indent, name, | |
341 | if ((flags & PRINT_OBJ_COMPACT) == 0): | |
342 | print >> out | |
343 | indent += 2 | |
344 | print >> out, " "*indent, "{", | |
345 | if ((flags & PRINT_OBJ_COMPACT) == 0): | |
346 | print >> out | |
347 | keys = object.keys() | |
348 | keys.sort() | |
2eeaec19 RD |
349 | for key in keys: |
350 | if (key != None): | |
351 | n = key | |
352 | if (not (isinstance(n, basestring))): | |
353 | n = str(n) | |
02b800ce RD |
354 | else: |
355 | n = nameToString(n, flags) | |
2eeaec19 | 356 | if ((not n.startswith("_") or ((flags & PRINT_OBJ_HIDE_INTERNAL) == 0))): |
02b800ce | 357 | if printObject(out, object[key], name=n, indent=indent+2, flags=(flags | PRINT_OBJ_INTERNAL), exclude=exclude, remove=remove, maxIndent=maxIndent): |
2eeaec19 RD |
358 | if ((flags & PRINT_OBJ_COMPACT) == 0): |
359 | print >> out | |
360 | else: | |
361 | print >> out, ",", | |
26ee3a06 RD |
362 | print >> out, " "*indent, "}", |
363 | elif (hasattr(object, "__dict__")): | |
02b800ce RD |
364 | if (name.startswith("_")): ## and ((flags & PRINT_OBJ_HIDE_INTERNAL) > 0)): |
365 | print >> out, " "*indent, name, " : ", typeToString(object, flags), | |
366 | elif ((exclude != None) and ((object in exclude) or (object.__dict__ in exclude))): | |
367 | print >> out, " "*indent, name, " : ", typeToString(object, flags), " (already printed)", | |
26ee3a06 RD |
368 | else: |
369 | if (exclude != None): exclude.append(object) | |
02b800ce RD |
370 | print >> out, " "*indent, name, " : ", typeToString(object, flags), |
371 | if ((flags & PRINT_OBJ_GETATTR) == 0): | |
372 | if ((flags & PRINT_OBJ_COMPACT) == 0): | |
373 | print >> out | |
374 | printObject(out, object.__dict__, indent=indent, flags=flags, exclude=exclude, remove=remove, maxIndent=maxIndent) | |
26ee3a06 | 375 | else: |
02b800ce RD |
376 | if ((flags & PRINT_OBJ_COMPACT) == 0): |
377 | print >> out | |
378 | ## indent += 2 | |
379 | print >> out, " "*indent, "{", | |
380 | keys = object.__dict__.keys() | |
381 | keys.sort() | |
382 | printed = True | |
383 | for key in keys: | |
384 | if ((exclude != None) and (key in exclude)): | |
385 | continue | |
386 | if (printed and ((flags & PRINT_OBJ_COMPACT) == 0)): | |
26ee3a06 | 387 | print >> out |
02b800ce RD |
388 | n = nameToString(key, flags) |
389 | printed = printObject(out, getattr(object, n), name=n, indent=indent+2, flags=flags, exclude=exclude, remove=remove, maxIndent=maxIndent) | |
390 | if ((flags & PRINT_OBJ_COMPACT) == 0): | |
391 | print >> out | |
392 | print >> out, " "*indent, "}", | |
26ee3a06 RD |
393 | elif (indent < 0): |
394 | print >> out, object, | |
395 | elif isinstance(object, basestring): | |
2eeaec19 | 396 | if ((exclude != None) and name in exclude): |
02b800ce | 397 | print >> out, " "*indent, name, " : ", typeToString(object, flags), " of length = ", len(object), " (excluded)", |
26ee3a06 | 398 | elif (len(object) > 100): |
02b800ce RD |
399 | object = toString(object, flags) |
400 | print >> out, " "*indent, name, ":", typeToString(object, flags), "[%d] = %s...%s" % (len(object), object[:50], object[-50:]), | |
26ee3a06 | 401 | else: |
02b800ce | 402 | print >> out, " "*indent, name, ":", typeToString(object, flags), "=", toString(object, flags), |
2eeaec19 RD |
403 | ## elif (isinstance(object, float)): |
404 | ## val = str(object) | |
405 | ## if (len(val) > 17): | |
406 | ## val = val[:17] | |
407 | ## print >> out, " "*indent, name, ":", type(object), "=", val, | |
26ee3a06 | 408 | else: |
02b800ce | 409 | print >> out, " "*indent, name, ":", typeToString(object, flags), "=", toString(object, flags), |
26ee3a06 RD |
410 | if (finalNewLine): |
411 | print >> out | |
412 | return printed |