Monday, March 7, 2011

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

When debugging in PHP I frequently find it useful to simply stick a var_dump($foo, $bar, ...) in my code to show me the the what a variable is, what is value is, and the same for anything that it contains.

What is a good python equivalent for this?

I have seen several things in my Google searching that are somewhat equivalent, but nothing that is the same or better.

From stackoverflow
  • print

    For your own classes, just def a __str__ method

  • To display a value nicely, you can use the pprint module. The easiest way to dump all variables with it is to do

    pprint.pprint(globals())
    pprint.pprint(locals())
    

    If you are running in CGI, a useful debugging feature is the cgitb module, which displays the value of local variables as part of the traceback.

  • PHP's var_export() usually shows a serialized version of the object that can be exec()'d to re-create the object. The closest thing to that in Python is repr()

    "For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]"

    Paul Biggar : I think you're thinking of `var_export`.
    Victor Farazdagi : yep, var_export in php and repr in python are somewhat related - that's if you want an official string representation of some object - you use repr(). In order to have non-official (read human-readable) you can always force conversion to string: str(object), which produces info similar to php's print_r() (used much more ofter for debugging than var_dump).
    mark : Please fix the answer, it's incorrect. As mentioned, either you're talking about var_export or describe var_dump() differently.
  • So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.

    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
    

    Here is the usage

    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))
    

    and the results.

    {'__type__': '<__main__.stdClass object at 0x2b126000b890>',
     'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
     'int': 1,
     'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
     'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
                'value': 'foobar'},
     'tup': (1, 2, 3, 4)}
    
    gradbot : +1, I found this useful.
  • I use self-written Printer class, but dir() is also good for outputting the instance fields/values.

    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)
    

    The sample of usage:

    Printer(MyClass)
    
  • I think the best equivalent to PHP's var_dump($foo, $bar) is:

    print vars(foo),vars(bar)

0 comments:

Post a Comment