Search code examples
pythondebuggingintrospectionpretty-printpython-datamodel

Is there a built-in function to print all the current properties and values of an object?


So what I'm looking for here is something like PHP's print_r function.

This is so I can debug my scripts by seeing what's the state of the object in question.


Solution

  • You are really mixing together two different things.

    Use dir(), vars() or the inspect module to get what you are interested in (I use __builtins__ as an example; you can use any object instead).

    >>> l = dir(__builtins__)
    >>> d = __builtins__.__dict__
    

    Print that dictionary however fancy you like:

    >>> print l
    ['ArithmeticError', 'AssertionError', 'AttributeError',...
    

    or

    >>> from pprint import pprint
    >>> pprint(l)
    ['ArithmeticError',
     'AssertionError',
     'AttributeError',
     'BaseException',
     'DeprecationWarning',
    ...
    
    >>> pprint(d, indent=2)
    { 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
      'AssertionError': <type 'exceptions.AssertionError'>,
      'AttributeError': <type 'exceptions.AttributeError'>,
    ...
      '_': [ 'ArithmeticError',
             'AssertionError',
             'AttributeError',
             'BaseException',
             'DeprecationWarning',
    ...
    

    Pretty printing is also available in the interactive debugger as a command:

    (Pdb) pp vars()
    {'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
                      'AssertionError': <type 'exceptions.AssertionError'>,
                      'AttributeError': <type 'exceptions.AttributeError'>,
                      'BaseException': <type 'exceptions.BaseException'>,
                      'BufferError': <type 'exceptions.BufferError'>,
                      ...
                      'zip': <built-in function zip>},
     '__file__': 'pass.py',
     '__name__': '__main__'}