October 24, 2007
Python introspection with the inspect module
Here are some fun and potentially useful tricks you can do using the inspect module.
Get a list of currently imported modules:
myglobals = dict()
myglobals.update(globals())
modules = [value
for key, value in myglobals.items()
if inspect.ismodule(value)]
Get a list of classes in a module (by Marc 'BlackJack' Rintsch):
from inspect import getmembers, isclass
classes = getmembers(module, isclass)
Get all "callables" (e.g. methods) in an object:
class Spam:
plumage = "lovely"
def __init__(self):
self.variety = "Norwegian Blue"
self.dead = lambda : not self.alive()
def alive(self):
return False
print "For Spam class"
for name, value in inspect.getmembers(Spam, callable):
print " Callable:", name
print "For Spam instance"
for name, value in inspect.getmembers(Spam(), callable):
print " Callable:", name
Output:
Callable: __init__
Callable: alive
For Spam instance
Callable: __init__
Callable: alive
Callable: dead
Get the file name and starting line number of an object:
def get_file_and_line_num(obj):
filename = inspect.getabsfile(obj)
source, line_num = inspect.findsource(obj)
return filename, line_num