def dump(obj):
'''return a printable representation of an object for debugging'''
newobj=obj
if '__dict__' in dir(obj):
newobj=obj.__dict__
if ' object at ' in str(obj) and not newobj.has_key('__type__'):
newobj['__type__']=str(obj)
for attr in newobj:
newobj[attr]=dump(newobj[attr])
return newobj
这是用法
class stdClass(object): pass
obj=stdClass()
obj.int=1
obj.tup=(1,2,3,4)
obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
obj.subObj=stdClass()
obj.subObj.value='foobar'
from pprint import pprint
pprint(dump(obj))
class Printer:
def __init__ (self, PrintableClass):
for name in dir(PrintableClass):
value = getattr(PrintableClass,name)
if '_' not in str(name).join(str(value)):
print ' .%s: %r' % (name, value)
def var_dump(var, prefix=''):
"""
You know you're a php developer when the first thing you ask for
when learning a new language is 'Where's var_dump?????'
"""
my_type = '[' + var.__class__.__name__ + '(' + str(len(var)) + ')]:'
print(prefix, my_type, sep='')
prefix += ' '
for i in var:
if type(i) in (list, tuple, dict, set):
var_dump(i, prefix)
else:
if isinstance(var, dict):
print(prefix, i, ': (', var[i].__class__.__name__, ') ', var[i], sep='')
else:
print(prefix, '(', i.__class__.__name__, ') ', i, sep='')
样例输出:
>>> var_dump(zen)
[list(9)]:
(str) hello
(int) 3
(int) 43
(int) 2
(str) goodbye
[list(3)]:
(str) hey
(str) oh
[tuple(3)]:
(str) jij
(str) llll
(str) iojfi
(str) call
(str) me
[list(7)]:
(str) coucou
[dict(2)]:
oKey: (str) oValue
key: (str) value
(str) this
[list(4)]:
(str) a
(str) new
(str) nested
(str) list