What is the __mro__ attribute and how does it relate to metaclasses?
Short answer
__mro__ is a tuple on every class showing its Method Resolution Order -- the linear sequence Python searches through when looking up an attribute or method, computed by the C3 linearization algorithm.
Advertisement
AModel answer
__mro__ is a tuple on every class showing its Method Resolution Order -- the linear sequence Python searches through when looking up an attribute or method, computed by the C3 linearization algorithm. Since ordinary classes are instances of the `type` metaclass, __mro__ itself is exposed as a class attribute accessible via ClassName.__mro__ or the equivalent ClassName.mro() method.
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__)
# (<class D>, <class B>, <class C>, <class A>, <class object>)Real-world example
Debugging a diamond-inheritance bug, a developer prints D.__mro__ to see the exact order Python will search for a method, revealing why C's override of a method is being used instead of B's.
Likely follow-ups
- How does C3 linearization differ from simple depth-first search?
- Can __mro__ be customized via a metaclass?
Related topics