itersubclasses

iteration_utilities.itersubclasses(cls, seen=None)

Iterate over the subclasses of cls. Recipe based on the snippet of Gabriel Genellina ([0]) but modified.

Parameters
clstype

The class for which to iterate over the subclasses.

seenset, None, optional

Classes to exclude from iteration or None if all subclasses should be returned. Default is None.

Returns
subclassesgenerator

The subclasses of cls.

References

0

http://code.activestate.com/recipes/576949/

Examples

It works with any class and also handles diamond inheritance structures:

>>> class A: pass
>>> class B(A): pass
>>> class C(B): pass
>>> class D(C): pass
>>> class E(C): pass
>>> class F(D, E): pass
>>> list(i.__name__ for i in itersubclasses(A))
['B', 'C', 'D', 'F', 'E']

There is mostly no need to specify seen but this can be used to exclude the class and all subclasses for it:

>>> [i.__name__ for i in itersubclasses(A, seen={C})]
['B']

And it also works for objects subclassing type:

>>> class Z(type): pass
>>> class Y(Z): pass
>>> [i.__name__ for i in itersubclasses(Z)]
['Y']

The reverse operation: To iterate over the superclasses is possible using the class_to_test.__mro__ attribute:

>>> [i.__name__ for i in F.__mro__]
['F', 'D', 'E', 'C', 'B', 'A', 'object']