Sub topic 2
Searching the class hierarchy with the MRO
The previous chapter covered where attributes live: the instance __dict__ and the class __dict__. This chapter covers how Python searches the class side when a name is not found on the class itself. I assume you can write classes with inheritance, know that super() exists, and have used dunder methods.
Why a class search order is needed
A class can have several parents, and those parents can share a common ancestor. When you write obj.name, Python needs one fixed answer to "which class's name do I use?" The answer is the class's method resolution order, or MRO. The MRO is a tuple of classes, stored in __mro__ on every class. Python searches it from left to right and uses the first class whose own __dict__ contains the name.
Despite the name, the MRO applies to every class attribute, not only methods. Data values, descriptors, and nested classes are all found the same way.
Reading the MRO
class A:
label = "A"
class B(A):
pass
class C(A):
label = "C"
class D(B, C):
pass
print([k.__name__ for k in D.__mro__]) # ['D', 'B', 'C', 'A', 'object']
print(D.label) # CD.label is "C", not "A". A depth-first search (D, B, A) would reach A before C. The MRO puts C ahead of A, because A is a parent of both B and C and must come after both of them.
Every MRO ends with object, since every class inherits from it. That is why names like __init__, __repr__, and __getattribute__ are always found, even on a class that defines none of them.
The search as a loop
The search is short enough to write in a few lines. It checks vars(base), which is the base's own __dict__. It does not use getattr, which would trigger a full lookup on each base and make the result circular.
def owner_of(cls, name):
for base in cls.__mro__:
if name in vars(base):
return base
return None
print(owner_of(D, "label").__name__) # C
print(owner_of(D, "__init__").__name__) # object
print(owner_of(D, "missing")) # NoneThis is the same loop as find_in_mro in the full lookup model that later chapters build. Its result is the raw object stored in the class dictionary. If that object is a descriptor, it has not been called yet. Whether it gets called, and when, is the subject of the chapters on the descriptor protocol and lookup precedence.
How the order is computed: C3 linearization
Python builds the MRO with the C3 linearization algorithm, once, when the class is created. You rarely need to run it by hand, but its rules explain the results you see.
| Rule | Meaning |
|---|---|
| Children before parents | A class always appears before any of its bases. |
| Local order kept | In `class D(B, C)`, `B` appears before `C`. |
| Monotonic | If `X` comes before `Y` in a parent's MRO, it still does in the child's. |
For D(B, C) the computation is D followed by a merge of three lists: the MRO of B (B, A, object), the MRO of C (C, A, object), and the list of direct bases (B, C). The merge repeatedly takes the first class that does not appear in the tail of any other list.
Bis first in the first list and not in any tail, so take it.Ais next, but it is in the tail ofC, A, object, so skip it and takeC.- Now
Ais free, thenobject.
The result is D, B, C, A, object.
When no consistent order exists
Some base lists contradict themselves. Bad(X, Y) below asks for X before Y, but Y is a subclass of X, so Y must come first.
class X:
pass
class Y(X):
pass
try:
class Bad(X, Y):
pass
except TypeError as e:
print(e) # Cannot create a consistent method resolution order (MRO) ...The error is raised at class definition time, not at lookup time. The fix is to reorder the bases (Bad(Y, X)) or to drop the redundant base, since Y already inherits from X.
The instance dictionary is not in the MRO
The MRO is a property of the class. The instance's __dict__ is separate and is consulted by a different step of object.__getattribute__. Setting an instance attribute does not change what the MRO search finds:
d = D()
d.label = "instance"
print(d.label) # instance
print(owner_of(type(d), "label").__name__) # Cd.label returns the instance value, but the class-side search still lands on C. Which one wins in a given situation depends on whether the class-side object is a data descriptor, which the next chapters cover. For an ordinary value like a string, the instance dictionary wins.
Cooperative super() uses the same order
super() is also built on the MRO. super().who() does not mean "my parent class". It means "the next class after this one in the MRO of type(self)".
class Base:
def who(self):
return ["Base"]
class Left(Base):
def who(self):
return ["Left"] + super().who()
class Right(Base):
def who(self):
return ["Right"] + super().who()
class Child(Left, Right):
def who(self):
return ["Child"] + super().who()
print(Child().who()) # ['Child', 'Left', 'Right', 'Base']
print([k.__name__ for k in Child.__mro__])
# ['Child', 'Left', 'Right', 'Base', 'object']Inside Left.who, super() reaches Right, which is not a parent of Left. It works because the MRO of the instance's type puts Right next. The same Left class used on its own would call Base directly.
Edge cases worth knowing
- Changes after creation are visible. The MRO stores classes, not copies of their dictionaries. If you add
Base.extra = 1after instances exist, those instances seeextraon their next lookup. CPython keeps an internal per-type cache of lookup results, but it invalidates the cache when a class dictionary changes, so you do not observe stale values. - The MRO is fixed per class. Changing
__bases__or__mro__on an existing class is not supported for general use. Treat the MRO as computed once at class creation. - Metaclasses can customize it.
type.mro()is the method that computes the order. A metaclass can override it, which is rare and mostly of interest to framework authors. - The metaclass is not in the MRO of its instances. For
class K: pass, the MRO ofKis(K, object). The metaclasstypeis not in it. Class-level lookups such asK.nameuse a separate step, covered in the chapter on lookup on classes and metaclasses. - Missing everywhere means failure. If no class in the MRO has the name, the search returns nothing, and the surrounding lookup raises
AttributeError, or calls__getattr__if the class defines one.
Summary of the working model
- Each class has an MRO tuple, computed with C3 at creation:
cls.__mro__. - Class-side lookup of
namescans that tuple and uses the firstvars(base)containing it. - The instance
__dict__is a separate store and is not part of the tuple. super()continues the scan from the position after the current class, in the MRO of the instance's type.- The object found is only a candidate. If it is a descriptor, the next chapters show what Python does with it.
Exercise
Given class P: pass, class Q(P): pass, class R(P): pass, class S(Q, R): pass, and P defines name = "P" while R defines name = "R", what does S().name return and what is S._mro? Then, if you add S().name = "inst" on an instance s (s.name = "inst"), what does s.name return, and does ownerof(S, "name") change?
Show answer
The MRO is (S, Q, R, P, object). Searching for name: S has none, Q has none, R has name = "R", so S().name returns "R" (P is never reached). After s.name = "inst", s.name returns "inst" because the instance dictionary is checked and "R" is an ordinary value, not a data descriptor. owner_of(S, "name") still returns R, since the MRO search only looks at class dictionaries.
Exercise
Why does class Bad(X, Y) raise TypeError when Y is a subclass of X, and how do you fix it?
Show answer
Listing X before Y requires X to come before Y in the MRO, but the "children before parents" rule requires Y (the child) to come before X. No order satisfies both, so C3 fails when the class is defined. Reorder the bases to class Bad(Y, X), or write class Bad(Y), since Y already inherits from X.