Tuesday, March 2, 2010

Re-implementing the python 'inspect' module (whoops)

I am working with python introspection to have plugins for a framework registered (mostly) automatically. Until I read this blog post I was writing most of it myself, based on how the unittesting framework registers tests. Now I know there is a python inspect module that does all the heavy lifting, and the unittest module should be using it :) I learnt some interesting things about python introspection along the way I thought I should record.

Here is my implmentation of
inspect.getmembers(testclasses,inspect.ismodule)
to get a list of modules (.py files) from a package (directory with __init__.py):

from types import ModuleType
list = dir(testclasses)
modules = filter(lambda x: getattr(testclasses,x).__class__ == ModuleType, list)

Similarly, I was going to get the testmethods using a filter and the following method:

def isTestMethod(attrname, theclass=theclass, prefix=settings.TEST_METHOD_PREFIX):
"""It is a test method if it is callable and starts with the prefix"""
return attrname.startswith(prefix) and hasattr(getattr(theclass, attrname), '__call__')

which can be replaced by
inspect.getmembers(theclass,inspect.ismethod)

No comments: