views:

1072

answers:

11

I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand whats 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 could would I need to print out it's contents? Is that even possible?

Thanks.

+6  A: 

First, read the source.

Second, use the dir() function.

S.Lott
I'd reverse that order.
bayer
The source is more informative than dir() and a better habit to develop.
S.Lott
I beg to differ. dir() is just so much quicker and in 99% of the cases let's you find out what you need in combination with help().
bayer
I agree with usuallyuseless. A lot of the time, a simple call to dir() will suffice, thus saving you the trouble of having to look through the source code.
musicfreak
+1  A: 

You can list the attributes of a object with dir() in the shell:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Of course, there is also the inspect module: http://docs.python.org/library/inspect.html#module-inspect

bayer
A: 
erenon
+10  A: 

Python has a strong set of introspection features.

Take a look at the following built-in functions:

  • type()
  • dir()
  • id()
  • getattr()
  • hasattr()
  • globals()
  • locals()
  • callable()

type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.

Here is an online resource worth perusing: Dive Into Python Chapter 4: The Power of Introspection

Brandon E Taylor
Didn't know the term was 'introspection'. That's a great help! Aswell as all the functons you've given me... Thank you!
littlejim84
property, classmethod and staticmethod are not related to introspection. These methods all create special types of objects that can be used to define classes with special behavior, but are of no help at inspecting those classes or constructs.
TokenMacGuy
Quite right. I got overzealous in my enumerating. I have edited my post accordingly. Thanks.
Brandon E Taylor
A: 

In addition if you want to look inside list and dictionaries, you can use pprint()

Glader
+1  A: 

pprint and dir together work great

lyrae
A: 

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__

Lakshman Prasad
+5  A: 

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.

Brian
+1  A: 

object.__dict__

mtasic
+1  A: 

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:

>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'

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.

Ryan Bright
+1  A: 

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.

Jason Baker