HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
objectbuiltfunctionandpropertiesthecurrentprintvaluesall

Problem

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': ,
  'AssertionError': ,
  'AttributeError': ,
...
  '_': [ 'ArithmeticError',
         'AssertionError',
         'AttributeError',
         'BaseException',
         'DeprecationWarning',
...


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

(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': ,
                  'AssertionError': ,
                  'AttributeError': ,
                  'BaseException': ,
                  'BufferError': ,
                  ...
                  'zip': },
 '__file__': 'pass.py',
 '__name__': '__main__'}

Code Snippets

>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__
>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...
>>> 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',
...
(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__'}

Context

Stack Overflow Q#192109, score: 822

Revisions (0)

No revisions yet.