]> git.saurik.com Git - wxWidgets.git/blob - wxPython/samples/ide/activegrid/util/objutils.py
DocView and ActiveGrid IDE updates from Morgan Hua:
[wxWidgets.git] / wxPython / samples / ide / activegrid / util / objutils.py
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
17 import __builtin__
18 import types
19 import activegrid.util.utillang as utillang
20 import activegrid.util.datetimeparser as datetimeparser
21 from types import *
22 from activegrid.util.lang import *
23
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
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
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
112 def classForName(className):
113 ctype = typeForName(className)
114 if (isinstance(ctype, (types.ClassType, types.TypeType))):
115 return ctype
116 return None
117
118 def newInstance(className, objargs=None):
119 "dynamically create an object based on the className and return it."
120
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
130 if className == "str" or className == "unicode": # don't strip: blanks are significant
131 if len(objargs) > 0:
132 try:
133 return utillang.unescape(objargs[0]).encode()
134 except:
135 return "?"
136 else:
137 return ""
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
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
158 def toDiffableRepr(value, maxLevel=None):
159 if (value == None):
160 return "None"
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)
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))
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__")):
184 s = str(value)
185 elif (hasattr(value, "__dict__")):
186 s = "%s(%s)" % (type(value), toDiffableString(value.__dict__, maxLevel))
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:
208 items.append(toDiffableString(v, maxLevel))
209 s = "[" + ", ".join(items) + "]"
210 elif (isinstance(value, dict)):
211 items = []
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)))
217 else:
218 items.append("'%s': %s" % (key, toDiffableString(val, maxLevel)))
219 s = "{" + ", ".join(items) + "}"
220 else:
221 s = str(value)
222 return s
223
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)
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)
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
258 def toString(value, options=0):
259 if ((options & PRINT_OBJ_DIFFABLE) > 0):
260 return toDiffableString(value)
261 elif (not isinstance(value, basestring)):
262 return str(value)
263 return value
264
265 def typeToString(obj, options=0):
266 if (isinstance(obj, BooleanType)):
267 return "bool"
268 elif (isinstance(obj, UnicodeType)):
269 if ((options & PRINT_OBJ_DIFFABLE) > 0):
270 return "string"
271 return "unicode"
272 elif (isinstance(obj, basestring)):
273 return "string"
274 elif (isinstance(obj, IntType)):
275 return "int"
276 elif (isinstance(obj, LongType)):
277 if ((options & PRINT_OBJ_DIFFABLE) > 0):
278 return "int"
279 return "long"
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)):
289 ## ds = str(type(obj))
290 ds = "<class %s.%s> " % (obj.__module__, obj.__class__.__name__)
291 else:
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
313
314 PRINT_OBJ_GETATTR = 1
315 PRINT_OBJ_HIDE_INTERNAL = 2
316 PRINT_OBJ_COMPACT = 4
317 PRINT_OBJ_NONONE = 8
318 PRINT_OBJ_DIFFABLE = 16
319 PRINT_OBJ_HIDE_EXCLUDED = 32
320 PRINT_OBJ_INTERNAL = 512
321
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
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):
332 print >> out
333 return True
334 finalNewLine = False
335 printed = True
336 if ((flags & (PRINT_OBJ_COMPACT | PRINT_OBJ_HIDE_EXCLUDED)) > 0):
337 if ((exclude != None) and ((object in exclude) or (name in exclude))):
338 return
339 if ((flags & PRINT_OBJ_COMPACT) > 0):
340 indent = 0
341 if ((flags & PRINT_OBJ_INTERNAL) == 0):
342 finalNewLine = True
343 flags |= PRINT_OBJ_INTERNAL
344 if (object is None):
345 if (flags & PRINT_OBJ_NONONE) == 0:
346 print >> out, " "*indent, name, " = None",
347 else:
348 finalNewLine = False
349 printed = False
350 elif (name.startswith("_") and ((flags & PRINT_OBJ_HIDE_INTERNAL) > 0) and not name.startswith("_v_")):
351 finalNewLine = False
352 printed = False
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)",
358 else:
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):
362 print >> out
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)",
367 else:
368 if ((exclude != None) and (len(object) > 0)): exclude.append(object)
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()
379 for key in keys:
380 if (key != None):
381 n = key
382 if (not (isinstance(n, basestring))):
383 n = str(n)
384 else:
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):
389 print >> out
390 else:
391 print >> out, ",",
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)",
398 else:
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):
403 print >> out
404 printObject(out, object.__dict__, indent=indent, flags=flags, exclude=exclude, remove=remove, maxIndent=maxIndent)
405 else:
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)):
417 print >> out
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, "}",
423 elif (indent < 0):
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:]),
431 else:
432 print >> out, " "*indent, name, ":", typeToString(object, flags), "=", toString(object, flags),
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,
438 else:
439 print >> out, " "*indent, name, ":", typeToString(object, flags), "=", toString(object, flags),
440 if (finalNewLine):
441 print >> out
442 return printed