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 would like to basically ‘look’ inside the Python objects to see how they tick – like their methods and properties.
So say I have a Python object, what would I need to print out its contents? Is that even possible?
>>>print inspect.getsource(inspect.getsource)def getsource(object):"""Return the text of the source code for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a single string. An
IOError is raised if the source code cannot be retrieved."""
lines, lnum = getsourcelines(object)return string.join(lines,'')
If this is for exploration to see what’s going on, I’d recommend looking at IPython. This adds various shortcuts to obtain an objects documentation, properties and even source code. For instance appending a “?” to a function will give the help for the object (effectively a shortcut for “help(obj)”, wheras using two ?’s (“func??“) will display the sourcecode if it is available.
There are also a lot of additional conveniences, like tab completion, pretty printing of results, result history etc. that make it very handy for this sort of exploratory programming.
For more programmatic use of introspection, the basic builtins like dir(), vars(), getattr etc will be useful, but it is well worth your time to check out the inspect module. To fetch the source of a function, use “inspect.getsource” eg, applying it to itself:
>>> print inspect.getsource(inspect.getsource)
def getsource(object):
"""Return the text of the source code for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a single string. An
IOError is raised if the source code cannot be retrieved."""
lines, lnum = getsourcelines(object)
return string.join(lines, '')
inspect.getargspec is also frequently useful if you’re dealing with wrapping or manipulating functions, as it will give the names and default values of function parameters.
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.
Others have already mentioned the dir() built-in which sounds like what you’re looking for, but here’s another good tip. Many libraries — including most of the standard library — are distributed in source form. Meaning you can pretty easily read the source code directly. The trick is in finding it; for example:
The *.pyc file is compiled, so remove the trailing ‘c’ and open up the uncompiled *.py file in your favorite editor or file viewer:
/usr/lib/python2.5/string.py
I’ve found this incredibly useful for discovering things like which exceptions are raised from a given API. This kind of detail is rarely well-documented in the Python world.
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))
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:
IPython. A python terminal that allows you to inspect using tab completion.
Eclipse with the PyDev plugin. It has an excellent debugger that allows you to break at a given spot and inspect objects by browsing all variables as a tree. You can even use the embedded terminal to try code at that spot or type the object and press ‘.’ to have it give code hints for you.
If you want to look inside a live object, then python’s inspect module is a good answer. In general, it works for getting the source code of functions that are defined in a source file somewhere on disk. If you want to get the source of live functions and lambdas that were defined in the interpreter, you can use dill.source.getsource from dill. It also can get the code for from bound or unbound class methods and functions defined in curries… however, you might not be able to compile that code without the enclosing object’s code.