How can I sort a list of Python classes by inheritance depth?
Simply sort by len(cls.mro())
.
If C2
is a subclass of C1
, it must hold that len(C1.mro()) < len(C2.mro())
(because each class in C1.mro()
must also appear in C2.mro()
). Therefore, you can simply sort by the length of the mro list:
class A(object): pass
class X(object): pass
class B(A, X): pass
class C(B): pass
class D(C): pass
sorted([B, C, A, D, X], key = lambda cls: len(cls.mro()))
=> [__main__.A, __main__.X, __main__.B, __main__.C, __main__.D]
To also support old-style classes, you can replace cls.mro()
with inspect.getmro(cls)
.