Sub topic 10
Multiple inheritance and the diamond problem
This chapter assumes you can define classes, write subclasses, override methods, and call super(). You should also know that Python looks up methods through a class's method resolution order (MRO).
Listing more than one parent
A class can name several parents in its definition. Python then has to decide which parent's method runs when more than one defines it.
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']D inherits from both B and C, and both of those inherit from A. This shape is called a diamond.
The diamond problem
The problem is that A is reachable through two paths. In some languages this raises two questions:
- Does
A's code run once or twice? - If
BandCboth override a method, which one wins?
Python answers both with the MRO. It computes one linear order of all ancestors and uses it for every lookup. Each class appears in that order exactly once, so A runs once.
How the order is built
Python uses the C3 linearization algorithm. You don't need to run it by hand, but two rules help you predict the result:
- A class always comes before its parents.
- The order in which you list the parents is preserved. In
class D(B, C),Bcomes beforeC.
For D, this gives D, B, C, A, object. A comes after both B and C because each of them is a subclass of A.
Cooperative `super()`
In a multiple inheritance hierarchy, super() does not mean "my parent class". It means "the next class after me in the MRO of the instance's type".
Trace D().hello():
D.helloruns and callssuper().hello(). The next class in the MRO isB.B.helloruns and callssuper().hello(). InsideB, the next class in the instance's MRO isC, notA.C.helloruns and callssuper().hello(). The next class isA.A.helloreturns["A"]without callingsuper().
The lists are joined on the way back, which produces ['D', 'B', 'C', 'A']. Every method in the chain runs once. This only works if every class calls super(). If B skipped the call, C would never run for a D instance.
Common errors
- Breaking the chain. A method that does not call
super()stops everything after it in the MRO. Do this only on purpose, in the last class of the chain. - Naming a parent directly. Writing
A.hello(self)insideBbypasses the MRO. In the diamond,Awould run twice andCwould be skipped. - Inconsistent order. Python raises
TypeErrorwhen no valid order exists, for exampleclass X(A, B)whereBis already a subclass ofA. List the more specific class first:class X(B, A). - Mismatched arguments. Each
__init__in a cooperative chain may be followed by a class you did not write. A common fix is to accept**kwargsand pass them on withsuper().__init__(**kwargs).
class A:
pass
class B(A):
pass
try:
class X(A, B):
pass
except TypeError as exc:
print("TypeError:", exc)Checking the order
Use __mro__ or mro() to see the order before you debug. If a method behaves unexpectedly, the answer is usually in this list.
Exercise
Given the classes A, B, C, and D from this chapter, what does D().hello() return if B.hello is changed to return ["B"] and no longer calls super()?
Show answer
It returns ['D', 'B']. D.hello calls super(), which reaches B.hello. B.hello returns without calling super(), so C and A never run.
Exercise
Why does class X(A, B) fail when B is a subclass of A?
Show answer
The first rule says a class must come before its parents. A would need to come before B because it is listed first, but B is a subclass of A, so B must come before A. No consistent order exists, so Python raises TypeError. Writing class X(B, A) fixes it.