I've seen plenty of examples of people extracting all of the classes from a module, usually something like:
# foo.py
class Foo:
pass
# test.py
import inspect
import foo
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
print obj
Awesome.
But I can't find out how to get all of the classes from the current module.
# foo.py
import inspect
class Foo:
pass
def print_classes():
for name, obj in inspect.getmembers(???): # what do I do here?
if inspect.isclass(obj):
print obj
# test.py
import foo
foo.print_classes()
This is probably something really obvious, but I haven't been able to find anything. Can anyone help me out?
I was able to get all I needed from the
dir
built in plusgetattr
.Though, it does come out looking like a hairball:
Note that the stdlib's Python class browser module uses static source analysis, so it only works for modules that are backed by a real
.py
file.What about
?
This is the line that I use to get all of the classes that have been defined in the current module (ie not imported). It's a little long according to PEP-8 but you can change it as you see fit.
This gives you a list of the class names. If you want the class objects themselves just keep obj instead.
This is has been more useful in my experience.
Try this:
In your context:
And even better:
Because
inspect.getmembers()
takes a predicate.I don't know if there's a 'proper' way to do it, but your snippet is on the right track: just add
import foo
to foo.py, doinspect.getmembers(foo)
, and it should work fine.