I'm trying to learn about introspection in Python. my ultimate goal is to be able to build a module "text database" of all modules that are in the sys.path, by discovering all candidate modules (I've already done that), importing all of them, and then introspecting on each module to discover its functions, globals and classes. But for now I am having a problem with the latter.
I would like to import a module and figure out the names of its defined functions, globals, and classes. Here's my attempt, file foo.py, which has a single function, class, and global defined: #!/usr/bin/env python def somefunction(i): i = i + 1 class someclass: def __init__(self): self.x = 0 self.y = 1 someglobal = 1.2 if __name__ == "__main__": # when run as a script import foo import inspect from inspect import * isfuncs = filter(lambda x: re.match("^is", x) and x, dir(inspect)) print isfuncs print filter(lambda x: re.match("some", x[0]) and x[0], getmembers(foo)) for f in isfuncs: exec('print "trying %20s: ",; print getmembers(foo, %s)' % (f, f)) the output of running it as a script is the following: ['isbuiltin', 'isclass', 'iscode', 'isdatadescriptor', 'isframe', 'isfunction', 'ismethod', 'ismethoddescriptor', 'ismodule', 'isroutine', 'istraceback'] [('someclass', <class foo.someclass at 0x40058ddc>), ('somefunction', <function somefunction at 0x40066a74>), ('someglobal', 1.2)] trying isbuiltin: [] trying isclass: [('someclass', <class foo.someclass at 0x40058ddc>)] trying iscode: [] trying isdatadescriptor: [] trying isframe: [] trying isfunction: [('somefunction', <function somefunction at 0x40066a74>)] trying ismethod: [] trying ismethoddescriptor: [] trying ismodule: [] trying isroutine: [('somefunction', <function somefunction at 0x40066a74>)] trying istraceback: [] I was trying to use inspect.getmembers(foo, <PRED>) with an appropriate predicate ("is" function). it looks like I am able to discover that 'someclass' is a class, and that 'somefunction' is a function (and also a routine, apparently). However, I cannot seem to discover that 'someglobal' is a global. How to do so? Thanks, -- Benjamin Rutt -- http://mail.python.org/mailman/listinfo/python-list