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
If you want to look at parameters and methods, as others have pointed out you may well use pprint
or dir()
If you want to see the actual value of the contents, you can do
object.__dict__
"""Visit http://diveintopython.net/"""
__author__ = "Mark Pilgrim (mark@diveintopython.org)"
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [e for e in dir(object) if callable(getattr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList])
if __name__ == "__main__":
print help.__doc__
First, read the source.
Second, use the dir()
function.
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.