Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain all subclasses (of a specific class) defined by a module?

Given a module module and a class MyClass, how to obtain a list of all subclasses of MyClass defined in module?

like image 342
Tobias Kienzler Avatar asked Dec 26 '22 20:12

Tobias Kienzler


1 Answers

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))
like image 60
alecxe Avatar answered Dec 28 '22 10:12

alecxe