How Do I Perform Introspection on an Object in Python 2.x?

Metahyperbolic picture Metahyperbolic · Feb 13, 2009 · Viewed 23.9k times · Source

I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property.

Similarly, I'd like to get a list of methods for that object, as well, plus any other information I could find on that method, such as number of arguments and their respective types.

I have a feeling that I am simply missing the correct jargon in my Google searches. Not that I want to derail with specifics, but it's Active Directory, so that's always fun.

Answer

unwind picture unwind · Feb 13, 2009

Well ... Your first stop will be a simple dir(object). This will show you all the object's members, both fields and methods. Try it in an interactive Python shell, and play around a little.

For instance:

> class Foo:
   def __init__(self):
    self.a = "bar"
    self.b = 4711

> a=Foo()
> dir(a)
['__doc__', '__init__', '__module__', 'a', 'b']