Hugo Santos bio photo

Hugo Santos

Twitter Google+ LinkedIn Github

Class inheritance check with __mro__

Consider the following code:

class A(object):
    pass
class B(A):
    pass
class C(B):
    pass
class D(C):
    pass

As you can see, D derives from C, which derives from B, which derives from A, which derives from object. In this example is very clear to see the relations between the classes. But usually, things get more complicated and you can’t figure out in a second how the classes fit together. Specially if there’s no documentation!

MRO stands for Method Resolution Order and defines the path to follow when calling methods belonging to super classes.

Use <your_class>.__mro__ to print a tuple which describes the order of the method resolution.

Let’s print out D.__mro__

>>> D.__mro__  # try also: [x.__name__ for x in D.__mro__]
(<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

How about if we change the defintion of D.

class A(object):
    pass

class B(A):
    pass

class C(B):
    pass

class D(C, B):
    pass
>>> D.__mro__
(<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

Python first looks in D, then in C, then in B, then in A and then in object.

But beware! Change the definition of D - class D(B, C): - and check its __mro__.