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?
Method 1: Using the dir() Function: We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.
To get the class name of an instance in Python: Use the type() function and __name__ to get the type or class of the Object/Instance. Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.
To list all functions in a Python module you can use dir(module).
In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports.
Try this:
import sys current_module = sys.modules[__name__]
In your context:
import sys, inspect def print_classes(): for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj): print(obj)
And even better:
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
Because inspect.getmembers()
takes a predicate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With