Introspect current module to get classes
Troy Melhase
troy at gci.net
Fri May 30 21:16:07 EDT 2003
Hi Edmund:
Put the following code in a module named "look_at_me.py":
class A(object):
pass
class B(A):
pass
class C(A):
pass
def list_local_classes():
this_mod = __import__(__name__)
return [val for val in this_mod.__dict__.values()
if isinstance(val, type)]
local_classes = list_local_classes()
Then fire up your python interpreter and try it out like this:
troy at marchhare tmp $ python
Python 2.2.2 (#1, Mar 19 2003, 01:56:47)
[GCC 3.2.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import look_at_me
>>> look_at_me.local_classes
[<class 'look_at_me.A'>, <class 'look_at_me.C'>, <class 'look_at_me.B'>]
>>>
You'll probably want to adjust the "if isinstance" check to your meet your
needs. Hope this helps,
-troy
Edmund wrote:
> 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