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