Given a module module
and a class MyClass
, how to obtain a list of all subclasses of MyClass
defined in module
?
You can use inspect.getmembers(). Assuming you have in mymodule.py
:
class A(object):
pass
class B(A):
pass
class C(A):
pass
here's how you can get all subclasses of A
:
import inspect
import mymodule
from mymodule import A
def is_subclass(o):
return inspect.isclass(o) and issubclass(o, A)
print inspect.getmembers(mymodule, predicate=is_subclass)
or, in short lambda
form:
print inspect.getmembers(mymodule,
predicate=lambda o: inspect.isclass(o) and \
issubclass(o, A))
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