I\'m starting to code in various projects using Python (including Django web development and Panda3D game development).
To help me understand what\'s going on, I wo
In addition if you want to look inside list and dictionaries, you can use pprint()
While pprint has been mentioned already by others I'd like to add some context.
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets, classes, or instances are included, as well as many other built-in objects which are not representable as Python constants.
pprint
might be in high-demand by developers with a PHP background who are looking for an alternative to var_dump().
Objects with a dict attribute can be dumped nicely using pprint()
mixed with vars(), which returns the __dict__
attribute for a module, class, instance, etc.:
from pprint import pprint
pprint(vars(your_object))
So, no need for a loop.
To dump all variables contained in the global or local scope simply use:
pprint(globals())
pprint(locals())
locals()
shows variables defined in a function.
It's also useful to access functions with their corresponding name as a string key, among other usages:
locals()['foo']() # foo()
globals()['foo']() # foo()
Similarly, using dir() to see the contents of a module, or the attributes of an object.
And there is still more.
Python has a strong set of introspection features.
Take a look at the following built-in functions:
type()
and dir()
are particularly useful for inspecting the type of an object and its set of attributes, respectively.
If you're interested in a GUI for this, take a look at objbrowser. It uses the inspect module from the Python standard library for the object introspection underneath.
I'm surprised no one's mentioned help yet!
In [1]: def foo():
...: "foo!"
...:
In [2]: help(foo)
Help on function foo in module __main__:
foo()
foo!
Help lets you read the docstring and get an idea of what attributes a class might have, which is pretty helpful.
pprint and dir together work great