code_junkie

What is a python equivalent of PHP's var_dump()

Nov 13th, 2011
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. import pprint
  2.  
  3. pprint.pprint(globals())
  4. pprint.pprint(locals())
  5.  
  6. def dump(obj):
  7. '''return a printable representation of an object for debugging'''
  8. newobj=obj
  9. if '__dict__' in dir(obj):
  10. newobj=obj.__dict__
  11. if ' object at ' in str(obj) and not newobj.has_key('__type__'):
  12. newobj['__type__']=str(obj)
  13. for attr in newobj:
  14. newobj[attr]=dump(newobj[attr])
  15. return newobj
  16.  
  17. class stdClass(object): pass
  18. obj=stdClass()
  19. obj.int=1
  20. obj.tup=(1,2,3,4)
  21. obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
  22. obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
  23. obj.subObj=stdClass()
  24. obj.subObj.value='foobar'
  25.  
  26. from pprint import pprint
  27. pprint(dump(obj))
  28.  
  29. {'__type__': '<__main__.stdClass object at 0x2b126000b890>',
  30. 'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
  31. 'int': 1,
  32. 'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
  33. 'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
  34. 'value': 'foobar'},
  35. 'tup': (1, 2, 3, 4)}
  36.  
  37. class Printer:
  38.  
  39. def __init__ (self, PrintableClass):
  40. for name in dir(PrintableClass):
  41. value = getattr(PrintableClass,name)
  42. if '_' not in str(name).join(str(value)):
  43. print ' .%s: %r' % (name, value)
  44.  
  45. Printer(MyClass)
Add Comment
Please, Sign In to add comment