Python: find all classes which inherit from this one?

<>

This question already has an answer here:

Answers


You want to use Widget.__subclasses__() to get a list of all the subclasses. It only looks for direct subclasses though so if you want all of them you'll have to do a bit more work:

def inheritors(klass):
    subclasses = set()
    work = [klass]
    while work:
        parent = work.pop()
        for child in parent.__subclasses__():
            if child not in subclasses:
                subclasses.add(child)
                work.append(child)
    return subclasses

N.B. If you are using Python 2.x this only works for new-style classes.


You can track inheritance with your own metaclass

import collections

class A(object):
    class __metaclass__(type):
        __inheritors__ = defaultdict(list)

        def __new__(meta, name, bases, dct):
            klass = type.__new__(meta, name, bases, dct)
            for base in klass.mro()[1:-1]:
                meta.__inheritors__[base].append(klass)
            return klass

class B(A):
    pass

class C(B):
    pass

>>> A.__inheritors__
defaultdict(<type 'list'>, {<class '__main__.A'>: [<class '__main__.B'>, <class '__main__.C'>], <class '__main__.B'>: [<class '__main__.C'>]})

Anything that is inherited from A or it's derived classes will be tracked. You will get full inheritance map when all the modules in your application are loaded.


# return list of tuples (objclass, name) containing all subclasses in callers' module
def FindAllSubclasses(classType):
    import sys, inspect
    subclasses = []
    callers_module = sys._getframe(1).f_globals['__name__']
    classes = inspect.getmembers(sys.modules[callers_module], inspect.isclass)
    for name, obj in classes:
        if (obj is not classType) and (classType in inspect.getmro(obj)):
            subclasses.append((obj, name))
    return subclasses

You have to walk through all objects in the global namespace (globals()) and check if the related object/class is a subclass of the some other class (check the Python docs for issubclass()).


Need Your Help

as3 calling a function in Main.as Document Class from another class

actionscript-3 function class scope

I am sure this is a popular question but I can't find the exact answer I need. I simply need to access a function or functions created in the Main.as document class. I have tried several methods an...

Can a jQuery plug-in be local to a module?

javascript jquery jquery-plugins module-pattern

I really like the JavaScript module pattern to encapsulate data and logic. I'm also using jQuery extensively. My question is this: