iteration_utilities.itersubclasses(cls, seen=None)

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

cls : type

The class for which to iterate over the subclasses.

seen : set, None, optional

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

subclasses : generator

The subclasses of cls.


[0](1, 2)


To get all subclasses for a set:

>>> from iteration_utilities import itersubclasses
>>> list(itersubclasses(set))

It even works with custom classes and diamond structures:

>>> class A(object): 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})]

And it also works for objects subclassing type:

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

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']