Sub topic 2
Searching the class hierarchy with the MRO
This chapter assumes you can write classes, use inheritance, and know that instances and classes each have a __dict__. It explains how Python decides which class to search first when an attribute is not on the instance.
Why the order matters
When you write obj.name, Python may have to look through several classes. With single inheritance the order is obvious: the class, then its parent, then the grandparent. With multiple inheritance, several paths lead to the same base class, so Python needs a fixed rule.
That rule is the method resolution order (MRO). It is a tuple of classes, stored in cls.__mro__. Python searches it from left to right and stops at the first class whose __dict__ contains the name.
Reading the MRO
class Base:
label = "Base"
class Left(Base):
pass
class Right(Base):
label = "Right"
class Child(Left, Right):
pass
for cls in Child.__mro__:
print(cls.__name__)
print(Child.label)The loop prints Child, Left, Right, Base, object, one per line. The last line prints Right.
Left comes before Right because that is the order in the class Child(Left, Right) line. Base comes after both, because a class always appears after all of its subclasses. So Right.label is found before Base.label, even though Left has no label of its own.
The rules behind the order
Python builds the MRO with the C3 linearization algorithm. You do not need to run it by hand, but two rules help you predict the result:
- A class always appears before its parents.
- If a class lists several parents, they keep the left-to-right order you wrote.
If no order can satisfy both rules, Python refuses to create the class and raises TypeError.
class X: pass
class Y(X): pass
try:
class Bad(X, Y):
pass
except TypeError as e:
print(e)Bad asks for X before Y, but Y is a subclass of X and must come first. The two rules conflict, so the class statement fails.
A diagram of the search
The arrows show the search order, not inheritance. Inheritance has Left and Right both pointing to Base. The MRO flattens that shape into one line.
Searching by hand
You can reproduce the search with a short helper. This is the same step used in the lookup model later in this tutorial.
_missing = object()
def find_in_mro(cls, name):
for base in cls.__mro__:
if name in vars(base):
return vars(base)[name]
return _missing
class A:
x = 1
class B(A):
pass
print(find_in_mro(B, "x"))
print(find_in_mro(B, "y") is _missing)This prints 1 and then True. The helper looks only at class dictionaries. It does not look at instances, and it does not call descriptors. Those steps come later.
Where `super()` fits
super() uses the same tuple. super().method() starts searching the MRO of the instance's class after the class that contains the call. This is why cooperative multiple inheritance works: each class calls the next one in a single shared order.
Common mistakes
- Expecting depth-first order. In the example above, a depth-first search would reach
BasethroughLeftbeforeRight, and would returnBase. The MRO does not do that. - Reading
__mro__on an instance. Usetype(obj).__mro__orobj.__class__.__mro__. - Forgetting
object. Every MRO ends with it, so names such as__repr__are found there if no earlier class defines them.
Exercise
Given class P: pass, class Q(P): pass, class R(P): pass and class S(Q, R): pass, what is S._mro_ in order of class names? If P and R both define a method f, and Q does not, which f does S().f() call?
Show answer
The MRO is S, Q, R, P, object. S().f() calls R.f, because R comes before P in the MRO and Q has no f.