Tuesday, October 7, 2008

Useful inspect module

Inspect module offers various useful functions to Python developers.
Here are four most basic and useful functions inspect module has.

Before showing them, I will just make a simple module (mymodule.py) for the example usages shown below. It has just one function and two classes.


#file mymodule.py


#f() just prints "hello"
def f():
return "hello"

class A(object):
def ma(self):
print "A_m"

class B(A):
def mb(self):
print "B_m"



getsource(object)
This function is probably the most useful one in the module, along with getabsfile().
It returns the source code where object is defined.
object can be a class, method, function, etc (not instance because an instance gets created dynamically).

>>> print inspect.getsource(mymodule.B)
class B(A):
def mb(self):
print "B_m"


getabsfile(object, _filename=None)
It returns the absolute path to the file where object is defined.

>>> print inspect.getabsfile(mymodule.A)
/Users/tamurakouichi/mymodule.py


getcomments(object)
Get lines of comments immediately preceding an object's source code.
the object can be a class, function, etc...

>>> print inspect.getcomments(mymodule.f)
#f() just prints "hello"


classify_class_attrs(object, predicate=None)
It returns a detailed information of attributes a class has.
It includes in what class a method is defined.

>>> for m in inspect.classify_class_attrs(mymodule.B):
... print m
...
...snip...
('ma', 'method', <class 'mymodule.A'>, <function ma at 0x260c30>)
('mb', 'method', <class 'mymodule.B'>, <function mb at 0x260c70>)



There are many many functions. inspect module is a friend of every Python users from beginners to byte code analysers.

No comments: