Coder Perfect

What’s the best way to look inside a Python object?


I’m starting to use Python to code in a variety of tasks (including Django web development and Panda3D game development).

I’d like to ‘see’ inside the Python objects to see how they work, such as their methods and properties, to better grasp what’s going on.

So, let’s assume I have a Python object. What would I need to print out the contents of it? Is it even possible to do so?

Asked by littlejim84

Solution #1

Python provides a comprehensive set of introspection capabilities.

Consider the following built-in features:

The functions type() and dir() are particularly handy for checking an object’s type and collection of attributes.

Answered by Brandon E Taylor

Solution #2


Answered by mtasic85

Solution #3

I’m shocked no one has mentioned seeking assistance yet!

In [1]: def foo():
   ...:     "foo!"

In [2]: help(foo)
Help on function foo in module __main__:


Help allows you to read the docstring and get a sense of what attributes a class may have, which is quite useful.

Answered by Jason Baker

Solution #4

First and foremost, read the source.

Second, using the dir() method.

Answered by S.Lott

Solution #5

IPython is a good place to start if you want to figure out what’s going on. This offers a number of shortcuts for getting documentation, properties, and even source code for an object. Appending a “?” to a function, for example, displays the object’s help (essentially a shortcut for “help(obj)”), whereas using two(“func??”) ?’s displays the sourcecode if it is available.

There are a number of other features, such as tab completion, attractive printing of results, and result history, that make it ideal for exploratory programming.

The basic builtins like dir(), vars(), getattr(), and others will be beneficial for more programmatic introspection, but the inspect module is well worth your effort. Use “inspect.getsource” to get the source of a function, for example, by 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. If you’re wrapping or manipulating functions, getargspec comes in handy because it displays the names and default values of function parameters.

Answered by Brian

Post is based on