Sub topic 9
Reading the Method Resolution Order
This chapter assumes you can write classes and subclasses, override methods, and call super() in a simple hierarchy. It builds on attribute lookup and super() from earlier chapters. Here you will learn to read the order Python searches classes, predict which method runs, and spot hierarchies Python refuses to build.
What the method resolution order is
Every class has a method resolution order, or MRO. The MRO is the list of classes Python searches, in order, when you look up an attribute or method on an instance. The first class in the list that defines the name wins.
You can see the MRO in two equivalent ways:
ClassName.__mro__returns a tuple of classes.ClassName.mro()returns a list of classes.
With single inheritance, the MRO is just the chain from the class up to object:
class Animal:
pass
class Dog(Animal):
pass
print([k.__name__ for k in Dog.__mro__]) # ['Dog', 'Animal', 'object']
print(Dog.mro() == list(Dog.__mro__)) # TrueEvery class ends with object, because every class inherits from it directly or indirectly.
When you look up obj.name, Python checks the instance's own __dict__ first (for ordinary attributes). If the name is not there, it walks the MRO of type(obj). Data descriptors, such as properties, are checked before the instance dictionary, but the class search still uses the MRO.
The order is fixed when the class is created
Python computes the MRO once, when the class statement runs. It depends only on the list of base classes and on their own MROs. Changing a method later does not change the order.
This matters for multiple inheritance. The order you write the bases in is part of the design:
class A:
def who(self):
return "A"
class B(A):
def who(self):
return "B"
class C(A):
def who(self):
return "C"
class D(B, C):
pass
class E(C, B):
pass
print(D().who()) # B
print(E().who()) # C
print([k.__name__ for k in D.__mro__]) # ['D', 'B', 'C', 'A', 'object']
print([k.__name__ for k in E.__mro__]) # ['E', 'C', 'B', 'A', 'object']D and E have the same parents in a different order, so they pick different methods. Neither class defines who() itself. The MRO alone decides.
How Python computes it: C3 linearization
Python uses an algorithm called C3 linearization. You rarely run it by hand, but knowing its rules explains why some orders are accepted and others rejected. The MRO of a class always satisfies these rules:
- A class comes before its parents.
- If a class lists several bases, they keep the left-to-right order you wrote.
- The order is consistent with the MRO of each base. If
BputsXbeforeY, every subclass ofBalso putsXbeforeY.
The algorithm builds the MRO of a class K like this:
- Start with
K. - Merge the MROs of each base, plus the list of the bases themselves.
- To merge, take the first class from the first list that does not appear in the tail (everything after the first item) of any other list. Add it to the result and remove it from every list. Repeat until the lists are empty.
- If no candidate qualifies, fail.
Here is the diamond D(B, C) worked through. The MRO of B is [B, A, object] and the MRO of C is [C, A, object]. The merge starts with these three lists:
[B, A, object][C, A, object][B, C]
| Step | Candidate | Decision | Result so far |
|---|---|---|---|
| 1 | `B` | Not in any tail, so take it | `D, B` |
| 2 | `A` | Appears in the tail of `[C, A, object]`, so skip. Try `C`, which is not in any tail, so take it | `D, B, C` |
| 3 | `A` | No longer blocked, so take it | `D, B, C, A` |
| 4 | `object` | Only item left | `D, B, C, A, object` |
The key step is step 2. A must wait because C is also a subclass of A, and a class always comes before its parents. That is why C is searched before A, even though A is B's parent.
The solid arrows show the search order. The dashed arrows show the real inheritance, which is why A must come after both B and C.
Finding which class provides a method
When behavior surprises you, ask which class in the MRO actually defines the name. This small helper answers that by checking each class's own namespace:
class A:
def who(self):
return "A"
def only_a(self):
return "only A"
class B(A):
def who(self):
return "B"
class C(A):
def who(self):
return "C"
class D(B, C):
pass
def provider(cls, name):
for klass in cls.__mro__:
if name in vars(klass):
return klass
return None
print(provider(D, "who").__name__) # B
print(provider(D, "only_a").__name__) # A
print(provider(D, "missing")) # Nonevars(klass) returns only what klass defines itself, not what it inherits. That is why the loop can tell which class in the chain owns the name.
super() follows the MRO, not the parent
The most common misreading of super() is that it calls "my parent class." It actually means "the next class after this one in the MRO of the instance's type." The next class can be a sibling.
class A:
def hello(self):
return ["A"]
class B(A):
def hello(self):
return ["B"] + super().hello()
class C(A):
def hello(self):
return ["C"] # does not call super()
class D(B, C):
pass
print(D().hello()) # ['B', 'C']
print(B().hello()) # ['B', 'A']The code in B.hello is identical in both calls, yet super() reaches a different class:
- For a
Binstance, the MRO isB, A, object, sosuper()insideBreachesA. - For a
Dinstance, the MRO isD, B, C, A, object, sosuper()insideBreachesC.
C.hello does not call super(), so the chain stops there and A.hello never runs for a D instance. In a cooperative hierarchy, every class in the chain must call super() for the whole chain to run.
When Python refuses: inconsistent MRO
Some base orders cannot satisfy all three rules at once. Python then raises TypeError when the class is defined, not when it is used:
class A:
pass
class B(A):
pass
try:
class C(A, B):
pass
except TypeError as exc:
print(exc)
# Cannot create a consistent method resolution order (MRO) for bases A, BWriting C(A, B) asks for A before B. But B is a subclass of A, so B must come first. The two requirements contradict each other. The fix is to reorder the bases, as in class C(B, A), or to drop the redundant base, since C(B) already inherits from A.
The general pattern is to list more specific classes before more general ones.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Assuming the first base always wins for every name | A name defined in a shared ancestor can still resolve through a different base, depending on the MRO | Print `__mro__` and use a `provider` helper |
| Listing a parent before its own subclass in the bases | `TypeError: Cannot create a consistent method resolution order` | Put the more specific class first |
| One class in a chain skips `super()` | Classes after it in the MRO never run | Make every cooperating class call `super()` |
| Reading `super()` as "the parent" | Wrong prediction in diamonds | Read it as "next in `type(self).__mro__`" |
| Checking only `Class.__bases__` | You see direct parents but not the search order | Use `__mro__`, which includes every ancestor |
A reading routine
For any unfamiliar hierarchy, work through these steps:
- Print
[k.__name__ for k in TheClass.__mro__]. - Scan left to right for the first class that defines the method name. That class runs first.
- If that method calls
super(), continue from the next class in the list, and repeat. - Check that every class in the chain either calls
super()or is meant to end the chain.
Exercise
Given the classes below, what does Z().run() return, and what is the MRO of Z?
class P:
def run(self):
return ["P"]
class Q(P):
def run(self):
return ["Q"] + super().run()
class R(P):
def run(self):
return ["R"] + super().run()
class Z(R, Q):
pass
Show answer
The MRO is Z, R, Q, P, object. Python takes R first (the left base), then Q, and P must wait until both R and Q are placed. Z().run() returns ['R', 'Q', 'P'], because R.run calls super(), which reaches Q (not P), Q.run calls super(), which reaches P, and P.run ends the chain.
Exercise
Why does class C(A, B) raise a TypeError when B is a subclass of A, and how do you fix it?
Show answer
The base order asks for A before B, but a class must come before its parents, so B has to come before A. These rules contradict each other, so no consistent MRO exists. Fix it by writing class C(B, A), or just class C(B), since B already inherits from A.
Exercise
In the diamond D(B, C) where B.hello calls super().hello() but C.hello does not, why does A.hello never run for a D instance?
Show answer
The MRO is D, B, C, A, object. B's super() call reaches C, the next class in the MRO. C.hello does not call super(), so the chain ends at C and A.hello is never reached.