Home Week 6 6.5 The Diamond Problem
WEEK 6 LESSON 5 OF 5

The Diamond Problem

What happens when two parents share a common ancestor?

What is the Diamond Problem?

The diamond problem occurs when a class D inherits from two classes B and C, and both B and C inherit from the same class A. This creates a diamond-shaped inheritance diagram. The question: if D calls a method from A, does it go through B or C? Could A's constructor run twice?

The Diamond Shape

    A
   / \
  B   C
   \ /
    D

Class D inherits from B and C. Both B and C inherit from A.

Seeing It in Action

class A:
    def __init__(self):
        print("A init")

class B(A):
    def __init__(self):
        super().__init__()
        print("B init")

class C(A):
    def __init__(self):
        super().__init__()
        print("C init")

class D(B, C):
    def __init__(self):
        super().__init__()
        print("D init")

d = D()
# Output:
# A init
# C init
# B init
# D init

Key observation: A's __init__ is called only once, not twice. Python's MRO ensures each class in the chain is visited exactly once.

Python's Solution: MRO

Python solves the diamond problem using Method Resolution Order (MRO) with C3 linearization. This algorithm guarantees that each class in the hierarchy is called exactly once, in a consistent and predictable order.

# See the exact resolution order
print(D.__mro__)
# (D, B, C, A, object)

# When D calls super().__init__():
# 1. D.__init__  calls super() -> goes to B
# 2. B.__init__  calls super() -> goes to C (not A!)
# 3. C.__init__  calls super() -> goes to A
# 4. A.__init__  calls super() -> goes to object
# 5. object.__init__ (does nothing)

Notice: When B calls super(), it does not go directly to A. It goes to C first (the next class in the MRO). This is how Python avoids calling A twice.

How to Avoid Issues

Always use super()

Never call parent methods directly (like A.__init__(self)). Using super() ensures the MRO is followed correctly.

Check the MRO

When in doubt, print ClassName.__mro__ to see exactly which order Python will use.

Prefer composition over deep inheritance

If the diamond is getting complex, consider using composition (having objects as attributes) instead of deep inheritance trees.

Best Practices

  • Always use super() -- never skip it in any class in the hierarchy.
  • Be aware of the MRO when designing class hierarchies with shared ancestors.
  • Keep inheritance trees as shallow as possible to minimize confusion.

Common Mistakes

Calling ParentClass.__init__(self) directly instead of using super(), which can cause the shared ancestor to be called multiple times.

Skipping super().__init__() in one of the middle classes, which breaks the MRO chain.

Assuming super() always calls the direct parent -- in diamond inheritance, it follows the MRO, which may skip to a sibling class first.

Practice Exercises

Exercise 1: Trace the Output

Recreate the A-B-C-D diamond example. Before running it, predict the output. Then run it and compare. Print D.__mro__ to verify.

Exercise 2: Diamond with Methods

Create a diamond where A has a greet() method, B and C override it differently. Call D().greet() and observe which version runs.

Exercise 3: Break and Fix

Modify the diamond example so that B calls A.__init__(self) directly instead of super().__init__(). Observe how A's init runs twice. Then fix it.

Week 6 Recap

Abstraction hides complexity and shows only what is needed.

Abstract classes define contracts using ABC and @abstractmethod.

Interfaces ensure consistency across different implementations.

Multiple inheritance adds flexibility but needs careful use.

The diamond problem is solved by Python's MRO, which ensures each class is called exactly once.

Summary

  • The diamond problem occurs when two parents share a common ancestor.
  • Python uses MRO (C3 linearization) to ensure each class is called once.
  • Always use super() to follow the MRO chain correctly.
  • Check ClassName.__mro__ to see the resolution order.
  • Next: Week 7 -- Real Projects! You will build complete applications using everything you have learned.