Roman Prykhodchenko Roman Prykhodchenko - 2 months ago 5x
Python Question

How can I find all subclasses of a class given its name?

I need a working approach of getting all classes that are inherited from the base class in Python.


New-style classes (i.e. subclassed from object, which is the default in Python 3) have a __subclasses__ method which returns the subclasses:

class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

Here are the names of the subclasses:

print([cls.__name__ for cls in vars()['Foo'].__subclasses__()])
# ['Bar', 'Baz']

Here are the subclasses themselves:

# [<class '__main__.Bar'>, <class '__main__.Baz'>]

Confirmation that the subclasses do indeed list Foo as their base:

for cls in vars()['Foo'].__subclasses__():
# <class '__main__.Foo'>
# <class '__main__.Foo'>

Note if you want subsubclasses, you'll have to recurse:

def all_subclasses(cls):
    return cls.__subclasses__() + [g for s in cls.__subclasses__()
                                   for g in all_subclasses(s)]

# [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]