reflection defined modules - How can I get a list of all classes within current module in Python?
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
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?
# Works on pretty much everything, but be mindful that # you get lists of strings back print dir(myproject) print dir(myproject.mymodule) print dir(myproject.mymodule.myfile) print dir(myproject.mymodule.myfile.myclass) # But, the string names can be resolved with getattr, (as seen below)
Though, it does come out looking like a hairball:
def list_supported_platforms(): """ List supported platforms (to match sys.platform) @Retirms: list str: platform names """ return list(itertools.chain( *list( # Get the class's constant getattr( # Get the module's first class, which we wrote getattr( # Get the module getattr(platforms, item), dir( getattr(platforms, item) ) ), 'SYS_PLATFORMS' ) # For each include in platforms/__init__.py for item in dir(platforms) # Ignore magic, ourselves (index.py) and a base class. if not item.startswith('__') and item not in ['index', 'base'] ) ))
If you want to have all the classes, that belong to the current module, you could use this :
import sys, inspect def print_classes(): is_class_member = lambda member: inspect.isclass(member) and member.__module__ == __name__ clsmembers = inspect.getmembers(sys.modules[__name__], is_class_member)
If you use Nadia's answer and you were importing other classes on your module, that classes will be being imported too.
So that's why
member.__module__ == __name__ is being added to the predicate used on
is_class_member. This statement checks that the class really belongs to the module.
A predicate is a function (callable), that returns a boolean value.
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.
import sys import inspect classes = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) if obj.__module__ is __name__]
This gives you a list of the class names. If you want the class objects themselves just keep obj instead.
classes = [obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) if obj.__module__ is __name__]
This is has been more useful in my experience.