Which Method Does Python Call? The MRO and C3 Linearization
This article explains how Python orders the classes of a hierarchy for attribute lookup, how the C3 linearization algorithm builds that order, which hierarchies have no valid order, and how super() follows it.
When a class inherits from several parents, and those parents share an ancestor, the question of which implementation of a method applies has more than one plausible answer. Python resolves it with a single rule, the method resolution order (MRO): a list of classes, computed once when the class is created, that every attribute lookup follows from left to right. The present article examines the diamond-shaped hierarchy that motivates the rule, the C3 linearization algorithm that builds the list, the hierarchies for which no valid order exists, and the way super() uses the same list to make multiple inheritance cooperative. A predictable order for every lookup is the secret weapon that makes multiple inheritance usable in Python.
The Diamond Problem
A diamond appears when two classes inherit from a common base and a fourth class inherits from both. The following example defines a Gadget base, two specializations, and a Smartphone that combines them; only Camera overrides the method charge.
class Gadget:
def turn_on(self):
return "gadget on"
def charge(self):
return "generic charger"
class Radio(Gadget):
def turn_on(self):
return "radio playing"
class Camera(Gadget):
def turn_on(self):
return "camera ready"
def charge(self):
return "camera battery"
class Smartphone(Radio, Camera):
pass
phone = Smartphone()
print([cls.__name__ for cls in Smartphone.__mro__])
# Output: ['Smartphone', 'Radio', 'Camera', 'Gadget', 'object']
print(phone.turn_on()) # Output: radio playing
print(phone.charge()) # Output: camera battery
The attribute __mro__, also available through the method mro(), shows the order in which Python searches for any attribute of a Smartphone. turn_on is found in Radio, the first parent listed. The second call is the instructive one: a depth-first search, which explores Radio and all its ancestors before Camera, would reach Gadget.charge first, but the MRO places the shared base Gadget after both of its children, so the more specific Camera.charge wins. The same list governs every attribute lookup, not only methods, a process examined in the article devoted to descriptors, and it also decides which implementation a generic function selects, as described in the article devoted to singledispatch.
Build Order: How C3 Linearizes a Hierarchy
Since Python 2.3, the MRO is computed with the C3 linearization algorithm. Its rule is recursive: the linearization of a class is the class itself followed by a merge of the linearizations of its parents and of the list of parents. The merge repeatedly takes the first candidate head of these lists that does not appear in the tail of any other list, which guarantees two properties: every class precedes its parents, and the order in which a class lists its parents is preserved in all of its subclasses. The following implementation reproduces the algorithm and compares its result with the one computed by the interpreter.
def c3(cls):
if cls is object:
return [object]
sequences = [c3(base) for base in cls.__bases__] + [list(cls.__bases__)]
result = [cls]
while any(sequences):
for sequence in sequences:
head = sequence[0] if sequence else None
if head and not any(head in other[1:] for other in sequences):
break
else:
raise TypeError("no consistent MRO")
result.append(head)
sequences = [[c for c in seq if c is not head] for seq in sequences]
return result
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print([cls.__name__ for cls in c3(D)]) # Output: ['D', 'B', 'C', 'A', 'object']
print(c3(D) == D.mro()) # Output: True
The class A cannot be taken after B, because it still appears in the tail of the linearization of C; it becomes a valid head only once C has been placed. This is the mechanism that moves a shared base behind all of its children. The implementation is a teaching aid: the interpreter computes the MRO in C when the class statement runs and stores the result in __mro__.
Hierarchies Without a Valid Order
C3 does not always succeed. When two parents impose contradictory orders on the same classes, no list can respect both, and Python refuses to create the class.
class X: pass
class Y: pass
class P(X, Y): pass
class Q(Y, X): pass
try:
class Z(P, Q): pass
except TypeError as error:
print(" ".join(str(error).split()))
# Output (CPython 3.12): Cannot create a consistent method resolution order (MRO) for bases X, Y
class Base: pass
class Child(Base): pass
try:
class Mixed(Base, Child): pass
except TypeError as error:
print(" ".join(str(error).split()))
# Output (CPython 3.12): Cannot create a consistent method resolution order (MRO) for bases Base, Child
P requires X before Y, and Q requires the opposite, so Z has no consistent order. The second case is a common mistake: listing a base class before its own subclass asks for Base to precede Child, which contradicts the rule that a class precedes its parents; the fix is simply to list Child alone, or the subclass first.
super() Follows the Instance's MRO
The function super() does not call "the parent class"; it continues the search in the MRO of the object's class, starting just after the class in which it is written. In a diamond, the next class may therefore be a sibling, which is what allows several classes to cooperate on the same method.
class Base:
def setup(self):
return ["Base"]
class Logging(Base):
def setup(self):
return ["Logging"] + super().setup()
class Caching(Base):
def setup(self):
return ["Caching"] + super().setup()
class Service(Logging, Caching):
def setup(self):
return ["Service"] + super().setup()
print(Service().setup()) # Output: ['Service', 'Logging', 'Caching', 'Base']
print(Logging().setup()) # Output: ['Logging', 'Base']
The same line, super().setup() inside Logging, calls Caching.setup for a Service and Base.setup for a plain Logging, because each instance brings its own MRO. Every implementation runs exactly once, and Base runs last. This cooperation works only if every class in the chain calls super(); a class that calls Base.setup(self) directly skips its siblings.
Pitfalls of Multiple Inheritance
The MRO makes multiple inheritance deterministic, but not necessarily intuitive. Five pitfalls are distinguished, which are the following:
- Depth-first intuition. The shared base of a diamond comes after all its children, not after the first branch.
- Order of the bases matters.
class Smartphone(Radio, Camera)andclass Smartphone(Camera, Radio)are different classes with different behaviour. - Inconsistent hierarchies. Contradictory parent orders, or a base listed before its subclass, raise
TypeErrorat class creation. - Broken cooperation. A method that calls a parent explicitly instead of using
super()stops the chain, so some classes never run. - Incompatible signatures. In a cooperative chain, each
super()call reaches a class that the author of the method may not know, so the methods must accept the same arguments, usually with**kwargs.
Choosing a Design
Consequently, multiple inheritance works best with small classes that each add one capability, and the following table summarizes the usual options.
| Situation | Recommended approach |
|---|---|
| A class combines independent capabilities | Mixins listed before the main base, each calling super() |
| Several classes extend the same method | Cooperative super() calls with compatible signatures |
| Inspecting which implementation applies | Class.__mro__ or Class.mro() |
| Contradictory or deep diamond hierarchies | Composition instead of inheritance |
| A family of classes with a required interface | A single abstract base class, as in the article devoted to abstract base classes |
Conclusion
It is concluded that the method resolution order turns multiple inheritance into a single, predictable list, computed by C3 so that every class precedes its parents and every class keeps the order of its bases. This magic also has a cost: some hierarchies have no valid order, and the position of a shared base contradicts the depth-first intuition. Because super() follows the MRO of the instance rather than the parent written in the code, it deserves a fuller treatment of its own, which is developed in a future article of this series.