Sub topic 10
Multiple inheritance and the diamond problem
This chapter assumes you can write a subclass, override a method, call super() in a method, and read a class's __mro__ (method resolution order). If any of those feel shaky, review the earlier chapters on super() and the method resolution order first.
Listing more than one base class
A class can name several parents in its definition. Python then treats the new class as a subtype of every one of them.
class Swimmer:
def move(self):
return "swims"
class Flyer:
def move(self):
return "flies"
class Duck(Swimmer, Flyer):
pass
print(Duck().move()) # swimsBoth parents define move(). Duck gets Swimmer's version because Swimmer is listed first. The order of the bases is part of the class's design, not a formality. It decides which parent wins when names collide.
You can confirm this with Duck.__mro__, which is (Duck, Swimmer, Flyer, object). Python searches that tuple from left to right and stops at the first class that defines the name.
The diamond problem
Multiple inheritance gets harder when two parents share a parent of their own. Class D inherits from B and C, and both of those inherit from A. On a diagram the four classes form a diamond.
The problem is this. If B, C and A all define hello(), and D calls its parents, which methods run, and in what order? Does A run twice, once through B and once through C? Some languages reach A twice, or force the programmer to choose a path by hand. Python gives one answer that holds for every class: it linearizes the hierarchy into a single list, and each class appears in that list exactly once.
How Python linearizes the hierarchy
Python builds the list with the C3 algorithm. You rarely run it by hand, but its two rules explain what you see:
- A class always comes before its own parents.
- If a class lists bases
(B, C), thenBcomes beforeCin the result.
For the diamond, rule 1 puts D first and A after both B and C. Rule 2 puts B before C. The only list that satisfies both is D, B, C, A, object.
Cooperative `super()`
In a single-inheritance chain, super() means "my parent". In a diamond that reading is wrong. super() really means "the next class after me in the MRO of the object's actual type". Here is the diamond with every class calling super():
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"] + super().hello()
class D(B, C):
def hello(self):
return ["D"] + super().hello()
print(D().hello()) # ['D', 'B', 'C', 'A']
print([k.__name__ for k in D.__mro__]) # ['D', 'B', 'C', 'A', 'object']Each class runs once, and A runs last. Notice what happens in B.hello(). The super() call there does not go to A. It goes to C, because C is the next class after B in D's MRO. B never mentions C, yet the chain passes through it.
The same B.hello() code behaves differently depending on the instance it runs on. This table shows the next class that super() reaches from inside B:
| Instance type | MRO | `super()` in `B` reaches |
|---|---|---|
| `B()` | `B, A, object` | `A` |
| `D()` | `D, B, C, A, object` | `C` |
Because of this, B cannot know at the time you write it what super() will return. Every class in the chain has to be written so that it works whichever class follows it. That is what "cooperative" means.
What breaks the chain
Cooperation fails if one class in the chain bypasses super() and names its parent directly. Here B calls A.hello(self) instead:
class A:
def hello(self):
return ["A"]
class B(A):
def hello(self):
return ["B"] + A.hello(self) # hard-coded parent
class C(A):
def hello(self):
return ["C"] + super().hello()
class D(B, C):
def hello(self):
return ["D"] + super().hello()
print(D().hello()) # ['D', 'B', 'A'] -- C was skippedC.hello() never runs. Nothing raises an error, so the bug is silent. If C did important setup or cleanup, that work is lost.
The rule is to use super() consistently. A hierarchy that mixes direct parent calls with super() calls will misbehave as soon as someone combines its classes in a diamond.
Cooperative constructors
Constructors are where this matters most, because the classes in a diamond usually take different arguments. Each class cannot know which class comes next, so it cannot know what that class needs. The usual pattern is for each __init__ to take its own arguments by name, and pass everything else along in **kwargs:
class A:
def __init__(self, **kwargs):
print("A init")
super().__init__(**kwargs)
class B(A):
def __init__(self, b, **kwargs):
print("B init")
self.b = b
super().__init__(**kwargs)
class C(A):
def __init__(self, c, **kwargs):
print("C init")
self.c = c
super().__init__(**kwargs)
class D(B, C):
def __init__(self, d, **kwargs):
print("D init")
self.d = d
super().__init__(**kwargs)
obj = D(b=1, c=2, d=3)
print(obj.b, obj.c, obj.d)This prints D init, B init, C init, A init, then 1 2 3. Each class takes the keyword it owns and forwards the rest. By the time the call reaches A, kwargs is empty, so A passes nothing on to object.__init__().
Two details keep this working:
- Use keyword arguments at the call site. With positional arguments, a class cannot tell which values belong to it once the order depends on the MRO.
- The class at the top of the hierarchy must not forward leftover arguments to
object.__init__().object.__init__()accepts no extra arguments, so a misspelled keyword such asD(b=1, c=2, d=3, e=4)ends in aTypeErrorat the top of the chain.
Orders Python refuses
Not every list of bases can be linearized. If the two C3 rules contradict each other, Python raises an error when it creates the class:
class A:
pass
class B(A):
pass
try:
class C(A, B):
pass
except TypeError as exc:
print(exc)The output is Cannot create a consistent method resolution order (MRO) for bases A, B. Listing A before B asks for the parent to come before its own child, which breaks rule 1. The fix is to reverse the bases to class C(B, A), or to drop A from the list, since B already inherits from it.
Other gotchas
- Base order changes behavior. Swapping
class D(B, C)toclass D(C, B)changes the MRO toD, C, B, A, and so changes which method wins and the order ofsuper()calls. super()inside a class is not a fixed name. It depends on the instance's type, so you cannot reason about it by reading one class alone. When debugging, printtype(self).__mro__.- Different signatures are fragile. If
B.save(self, path)andC.save(self)coexist in a diamond, a cooperative call from one to the other fails. Keep method signatures in a shared hierarchy compatible, or accept*args, **kwargsand pass them on. - Some built-in types cannot be combined. Two classes that inherit from different built-ins with incompatible internal layouts, such as
intandlist, raise aTypeErrorabout a layout conflict.
When to use it
Multiple inheritance is a good fit when each parent supplies a separate, narrow behavior and the parents do not depend on each other. The next chapter covers mixins, which apply this idea. It is a poor fit when the parents are full classes with their own state and overlapping method names, because then the MRO decides behavior that a reader cannot see by looking at one class.
If you cannot explain the MRO of a class in a sentence, consider whether composition would be simpler. A later chapter covers that choice.
Exercise
Given the classes below, what does Z().who() return, and what is Z's MRO?
class P:
def who(self):
return ["P"]
class Q(P):
def who(self):
return ["Q"] + super().who()
class R(P):
def who(self):
return ["R"] + super().who()
class Z(R, Q):
def who(self):
return ["Z"] + super().who()
Show answer
The MRO is Z, R, Q, P, object, because Z lists R before Q and P must come after both. Z().who() returns ['Z', 'R', 'Q', 'P']. The super() call in R goes to Q, not P, because Q is next in Z's MRO.
Exercise
A class Logged(Base) has __init__(self, name) that sets self.name = name and does not call super().__init__(). A second class Timed(Base) has __init__(self, interval) that sets self.interval = interval and does call super().__init__(). You define class Both(Logged, Timed). What goes wrong, and how do you fix both classes so Both(name="x", interval=5) works?
Show answer
Logged never calls super()._init(), so the chain stops there and Timed.init never runs, leaving interval unset. The signatures also do not accept each other's arguments. Fix both by taking only their own keyword and forwarding the rest: def init(self, name, **kwargs): self.name = name; super().init(**kwargs), and the same for Timed with interval. Base.init must also accept **kwargs and not forward leftovers to object.init_().