Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a list of Python classes by inheritance depth?

How would I sort a list of classes in Python, making sure that any child class is before any of its parent classes in the list?

I ask because I want to see what type out of a list of types, an object belongs to, but find the most specific type, if it belongs to multiple.

like image 469
saul.shanabrook Avatar asked May 14 '14 16:05

saul.shanabrook


People also ask

How do I sort a Python list by class?

Attrgetter Function There is still yet another way we can sort objects of a class in Python. Another way we can do is through the use of the attrgetter() function in Python. This function can get the attribute of an object so that the sorted() function can sort the objects of the class.

Does the order of inheritance matter in multiple inheritance?

Yes, you can do multiple inheritance. please note the order of class in ExampleSimMod matters.

Does order of inheritance matter in Python classes?

When we search for an attribute in a class that is involved in python multiple inheritance, an order is followed. First, it is searched in the current class. If not found, the search moves to parent classes. This is left-to-right, depth-first.

Can you sort a Python list?

Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.


1 Answers

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).

like image 140
shx2 Avatar answered Sep 19 '22 10:09

shx2