1 #----------------------------------------------------------------------------
3 # Purpose: Object Utilities
5 # Author: Alan Mullendore
9 # Copyright: (c) 2004-2005 ActiveGrid, Inc.
10 # License: wxWindows License
11 #----------------------------------------------------------------------------
19 import activegrid
.util
.utillang
as utillang
20 import activegrid
.util
.datetimeparser
as datetimeparser
22 from activegrid
.util
.lang
import *
24 FUNCTION_HAS_ATTR
= '_hasAttr'
25 FUNCTION_GET_ATTR
= '_getAttr'
26 FUNCTION_SET_ATTR
= '_setAttr'
27 FUNCTION_DEL_ATTR
= '_delAttr'
29 def hasRawAttr(obj
, name
):
32 if name
!= FUNCTION_HAS_ATTR
and hasattr(obj
, FUNCTION_HAS_ATTR
):
33 return obj
._hasAttr
(name
)
34 return obj
.__dict
__.has_key(name
)
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
)
41 def setRawAttr(obj
, name
, value
):
42 if name
!= FUNCTION_SET_ATTR
and hasattr(obj
, FUNCTION_SET_ATTR
):
43 obj
._setAttr
(name
, value
)
45 obj
.__dict
__[name
] = value
47 def delRawAttr(obj
, name
):
48 if name
!= FUNCTION_DEL_ATTR
and hasattr(obj
, FUNCTION_DEL_ATTR
):
51 del obj
.__dict
__[name
]
53 def getStaticAttr(obj
, attr
):
54 if (isinstance(obj
, types
.TypeType
)):
57 classDesc
= obj
.__class
__
58 if (hasattr(classDesc
, attr
)):
59 return getattr(classDesc
, attr
)
62 def setStaticAttr(obj
, attr
, value
):
63 if (isinstance(obj
, types
.TypeType
)):
66 classDesc
= obj
.__class
__
67 setattr(classDesc
, attr
, value
)
69 def hasAttrFast(obj
, name
):
70 if hasRawAttr(obj
, name
):
72 if hasattr(obj
, '_complexType'):
73 complexType
=obj
._complexType
74 element
=complexType
.findElement(name
)
77 if hasattr(obj
, name
):
81 def moduleForName(moduleName
):
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
]
94 def typeForName(typeName
):
95 i
= typeName
.rfind('.')
97 module
= moduleForName(typeName
[:i
])
100 if (name
in module
.__dict
__):
101 return module
.__dict
__[name
]
102 elif __builtin__
.__dict
__.has_key(typeName
):
103 return __builtin__
.__dict
__[typeName
]
106 def functionForName(functionName
):
107 ftype
= typeForName(functionName
)
108 if (isinstance(ftype
, (types
.FunctionType
, types
.MethodType
, types
.BuiltinFunctionType
, types
.BuiltinMethodType
))):
112 def classForName(className
):
113 ctype
= typeForName(className
)
114 if (isinstance(ctype
, (types
.ClassType
, types
.TypeType
))):
118 def newInstance(className
, objargs
=None):
119 "dynamically create an object based on the className and return it."
121 if not isinstance(objargs
, list):
124 if className
== "None":
126 elif className
== "bool":
127 if ((len(objargs
) < 1) or (objargs
[0].lower() == "false") or (not objargs
[0])):
130 if className
== "str" or className
== "unicode": # don't strip: blanks are significant
133 return utillang
.unescape(objargs
[0]).encode()
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)
146 classtype
= classForName(className
)
147 if (classtype
== None):
148 raise Exception("Could not find class %s" % className
)
150 if (len(objargs
) > 0):
151 return classtype(*objargs
)
155 def getClassProperty(classType
, propertyName
):
156 return getattr(classType
, propertyName
)
158 def toDiffableRepr(value
, maxLevel
=None):
161 if (maxLevel
== None):
165 return typeToString(value
, PRINT_OBJ_DIFFABLE
)
166 ## if ((exclude != None) and not isinstance(value, (basestring, int))):
169 ## return "<recursive reference>"
170 ## exclude.append(value)
171 ## elif (isinstance(value, ObjectType) and hasattr(value, "__dict__")):
172 ## if (exclude == None):
174 ## s = "%s(%s)" % (type(value), toDiffableString(value.__dict__, exclude))
175 if (not isinstance(value
, (BooleanType
, ClassType
, ComplexType
, DictType
, DictionaryType
,
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
))):
181 if (hasattr(value
, "_toDiffableString")):
182 s
= value
._toDiffableString
(maxLevel
)
183 elif (hasattr(value
, "__str__")):
185 elif (hasattr(value
, "__dict__")):
186 s
= "%s(%s)" % (type(value
), toDiffableString(value
.__dict
__, maxLevel
))
189 ix2
= s
.find(" object at 0x")
193 s
= "<class %s>" %s[ix
+1:ix2
]
194 elif (isinstance(value
, bool)):
199 elif (isinstance(value
, (tuple, list))):
202 if (isinstance(v
, basestring
)):
203 if (v
.find("'") >= 0):
204 items
.append('"%s"' % v
)
206 items
.append("'%s'" % v
)
208 items
.append(toDiffableString(v
, maxLevel
))
209 s
= "[" + ", ".join(items
) + "]"
210 elif (isinstance(value
, dict)):
212 for key
, val
in value
.iteritems():
213 if (isinstance(val
, UnicodeType
)):
214 items
.append("'%s': u'%s'" % (key
, toDiffableString(val
, maxLevel
)))
215 elif (isinstance(val
, basestring
)):
216 items
.append("'%s': '%s'" % (key
, toDiffableString(val
, maxLevel
)))
218 items
.append("'%s': %s" % (key
, toDiffableString(val
, maxLevel
)))
219 s
= "{" + ", ".join(items) + "}"
224 def toDiffableString(value
, maxLevel
=None):
225 ## if (value == None):
227 ## if ((exclude != None) and not isinstance(value, (basestring, int))):
230 ## return "<recursive reference>"
231 ## exclude.append(value)
232 s
= toDiffableRepr(value
, maxLevel
)
242 i
= s
.find(" at 0x", start
)
244 i
= ds
.find("\\src\\")
248 ds
= ds
.replace("\\", "/")
251 if (ds
[i
:i
+5] == "\\php\\"):
253 elif (ds
[i
:i
+8] == "\\python\\"):
255 ds
= "filepath: ..." + ds
[i
:]
258 def toString(value
, options
=0):
259 if ((options
& PRINT_OBJ_DIFFABLE
) > 0):
260 return toDiffableString(value
)
261 elif (not isinstance(value
, basestring
)):
265 def typeToString(obj
, options
=0):
266 if (isinstance(obj
, BooleanType
)):
268 elif (isinstance(obj
, UnicodeType
)):
269 if ((options
& PRINT_OBJ_DIFFABLE
) > 0):
272 elif (isinstance(obj
, basestring
)):
274 elif (isinstance(obj
, IntType
)):
276 elif (isinstance(obj
, LongType
)):
277 if ((options
& PRINT_OBJ_DIFFABLE
) > 0):
280 elif (isinstance(obj
, FloatType
)):
282 elif (type(obj
) == ListType
):
284 elif (isinstance(obj
, DictType
)):
286 elif (isinstance(obj
, TupleType
)):
288 elif (isinstance(obj
, InstanceType
)):
289 ## ds = str(type(obj))
290 ds
= "<class %s.%s> " % (obj
.__module
__, obj
.__class
__.__name
__)
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 ")):
301 ds
= "<class %s>" % ds
[ix
+1:-2]
304 def nameToString(name
, options
=0):
305 if (name
.startswith("_v_")):
307 if ((options
& PRINT_OBJ_DIFFABLE
) > 0):
309 if ((ix
> 1) and name
.startswith("_")):
311 return toDiffableString(name
)
314 PRINT_OBJ_GETATTR
= 1
315 PRINT_OBJ_HIDE_INTERNAL
= 2
316 PRINT_OBJ_COMPACT
= 4
318 PRINT_OBJ_DIFFABLE
= 16
319 PRINT_OBJ_HIDE_EXCLUDED
= 32
320 PRINT_OBJ_INTERNAL
= 512
322 def printObject(out
, object, name
=None, indent
=0, flags
=0, exclude
=None, remove
=None, maxIndent
=30):
325 ## elif (name.endswith("_") and not name.endswith("__")):
327 if ((remove
!= None) and (name
in asDict(remove
))):
329 if ((maxIndent
!= None) and (indent
> maxIndent
)):
330 print >> out
, " "*indent
, "%s: %s" % (name
, toString(str(object), flags
)),
331 if ((flags
& PRINT_OBJ_INTERNAL
) == 0):
336 if ((flags
& (PRINT_OBJ_COMPACT | PRINT_OBJ_HIDE_EXCLUDED
)) > 0):
337 if ((exclude
!= None) and ((object in exclude
) or (name
in exclude
))):
339 if ((flags
& PRINT_OBJ_COMPACT
) > 0):
341 if ((flags
& PRINT_OBJ_INTERNAL
) == 0):
343 flags |
= PRINT_OBJ_INTERNAL
345 if (flags
& PRINT_OBJ_NONONE
) == 0:
346 print >> out
, " "*indent
, name
, " = None",
350 elif (name
.startswith("_") and ((flags
& PRINT_OBJ_HIDE_INTERNAL
) > 0) and not name
.startswith("_v_")):
353 elif (isinstance(object, (list, tuple))):
354 if ((exclude
!= None) and object in exclude
):
355 print >> out
, " "*indent
, name
, " : ", typeToString(object, flags
), " of length = ", len(object), " (already printed)",
356 elif ((exclude
!= None) and name
in exclude
):
357 print >> out
, " "*indent
, name
, " : ", typeToString(object, flags
), " of length = ", len(object), " (excluded)",
359 if ((exclude
!= None) and (len(object) > 0)): exclude
.append(object)
360 print >> out
, " "*indent
, name
, " : ", typeToString(object, flags
), " of length = %d" % len(object),
361 for i
, o
in enumerate(object):
363 printObject(out
, o
, name
="[%d]" % i
, indent
=indent
+2, flags
=flags
, exclude
=exclude
, remove
=remove
, maxIndent
=maxIndent
)
364 elif (isinstance(object, dict)):
365 if ((exclude
!= None) and object in exclude
):
366 print >> out
, " "*indent
, name
, " : ", typeToString(object, flags
), " (already printed)",
368 if ((exclude
!= None) and (len(object) > 0)): exclude
.append(object)
370 print >> out
, " "*indent
, name
,
371 if ((flags
& PRINT_OBJ_COMPACT
) == 0):
374 print >> out
, " "*indent
, "{",
375 if ((flags
& PRINT_OBJ_COMPACT
) == 0):
382 if (not (isinstance(n
, basestring
))):
385 n
= nameToString(n
, flags
)
386 if ((not n
.startswith("_") or ((flags
& PRINT_OBJ_HIDE_INTERNAL
) == 0))):
387 if printObject(out
, object[key
], name
=n
, indent
=indent
+2, flags
=(flags | PRINT_OBJ_INTERNAL
), exclude
=exclude
, remove
=remove
, maxIndent
=maxIndent
):
388 if ((flags
& PRINT_OBJ_COMPACT
) == 0):
392 print >> out
, " "*indent
, "}",
393 elif (hasattr(object, "__dict__")):
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)",
399 if (exclude
!= None): exclude
.append(object)
400 print >> out
, " "*indent
, name
, " : ", typeToString(object, flags
),
401 if ((flags
& PRINT_OBJ_GETATTR
) == 0):
402 if ((flags
& PRINT_OBJ_COMPACT
) == 0):
404 printObject(out
, object.__dict
__, indent
=indent
, flags
=flags
, exclude
=exclude
, remove
=remove
, maxIndent
=maxIndent
)
406 if ((flags
& PRINT_OBJ_COMPACT
) == 0):
409 print >> out
, " "*indent
, "{",
410 keys
= object.__dict
__.keys()
414 if ((exclude
!= None) and (key
in exclude
)):
416 if (printed
and ((flags
& PRINT_OBJ_COMPACT
) == 0)):
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):
422 print >> out
, " "*indent
, "}",
424 print >> out
, object,
425 elif isinstance(object, basestring
):
426 if ((exclude
!= None) and name
in exclude
):
427 print >> out
, " "*indent
, name
, " : ", typeToString(object, flags
), " of length = ", len(object), " (excluded)",
428 elif (len(object) > 100):
429 object = toString(object, flags
)
430 print >> out
, " "*indent
, name
, ":", typeToString(object, flags
), "[%d] = %s...%s" % (len(object), object[:50], object[-50:]),
432 print >> out
, " "*indent
, name
, ":", typeToString(object, flags
), "=", toString(object, flags
),
433 ## elif (isinstance(object, float)):
435 ## if (len(val) > 17):
437 ## print >> out, " "*indent, name, ":", type(object), "=", val,
439 print >> out
, " "*indent
, name
, ":", typeToString(object, flags
), "=", toString(object, flags
),