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

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


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']


How about something like:

>>> o=object()>>> [(a,type(o.__getattribute__(a))) for a in dir(o)][('__class__', <type 'type'>), ('__delattr__', <type 'method-wrapper'>), ('__doc__', <type 'str'>), ('__format__', <type 'builtin_function_or_method'>),('__getattribute__', <type 'method-wrapper'>), ('__hash__', <type 'method-wrapper'>),('__init__', <type 'method-wrapper'>), ('__new__', <type 'builtin_function_or_method'>),('__reduce__', <type 'builtin_function_or_method'>),('__reduce_ex__', <type 'builtin_function_or_method'>),('__repr__', <type 'method-wrapper'>), ('__setattr__', <type 'method-wrapper'>),('__sizeof__', <type 'builtin_function_or_method'>),('__str__', <type 'method-wrapper'>),('__subclasshook__', <type 'builtin_function_or_method'>)]>>> 

A more structured method will be to use the inspect module:

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.