Python › Multiple Inheritance & MRO

What is the 'diamond problem', and how does Python's MRO solve it?

Intermediate

Answer

The diamond problem occurs when a class inherits from two classes that both inherit from a common ancestor, creating ambiguity about which inherited method version should be used. Python resolves this deterministically using the C3 linearization algorithm to compute a single, consistent Method Resolution Order (MRO), ensuring each ancestor class appears exactly once and in a predictable sequence that respects both local precedence order and each parent's own MRO.
class A:
    def greet(self): return 'A'

class B(A):
    def greet(self): return 'B'

class C(A):
    def greet(self): return 'C'

class D(B, C):  # diamond: D -> B,C -> A
    pass

print(D().greet())  # 'B' -- follows MRO, not naive depth-first
Real-world example A framework's mixin-based class hierarchy relies on predictable MRO resolution so that combining LoggingMixin and CachingMixin with a base Service class always calls the expected overridden method.

Common follow-ups: What does D.__mro__ show for this example?;How is C3 different from Python 2's classic depth-first MRO?