Introspect current module to get classes
Sean Ross
sross at connectmail.carleton.ca
Thu May 29 20:51:57 EDT 2003
This code seems to be doing what you're asking for, although, in this case,
I'm just accumulating a list of the names of the classes in this module, as
opposed to a list of the actual classes themselves. For the latter behaviour
just replace
classes = [key for key, value ...
with
classes = [value for key, value ...
import inspect
# import a class from some other module to see
# whether our filter handle it properly, i.e. ignore it
from test import MyClass
class A:
pass
class B:
pass
classes = [key for key,value in globals().items()
if inspect.isclass(value) and
value.__module__=='__main__']
print classes
"""
OUTPUTS:
['A', 'B']
imported class, 'MyClass', is filtered out of 'classes' by:
value.__module__=='__main__'
"""
"Edmund" <no.spam at address.com> wrote in message
news:8g3ddvcotfltqoj7d99nvooall46h6qko5 at 4ax.com...
> I have a module that needs to do some initialization based on a list
> of classes defined in itself.
>
> There has to be a way to determine what classes are defined in a
> module (and not imported, etc.), within the module itself, but I can't
> figure out how... Can anybody help?
>
> Thanks!
>
> ...Edmund.
More information about the Python-list
mailing list