Navigation

Python

How to Handle Method Resolution Order (MRO)

Demystify Python's Method Resolution Order to master multiple inheritance without the headaches of the dreaded diamond problem.

Table Of Contents

The Multiple Inheritance Maze

Multiple inheritance sounds great until you hit the diamond problem: when a class inherits from two classes that share a common ancestor. Which method gets called? In what order? Python's MRO has the answers.

Visualizing the Resolution Path

# Diamond inheritance example
class A:
    def method(self):
        print("A method")

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

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

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

# Check MRO
print(D.__mro__)
# (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)

# Or use mro() method
print(D.mro())

# Call method to see the order
d = D()
d.method()
# Output:
# D method
# B method
# C method
# A method

# Practical example with mixins
class LoggerMixin:
    def log(self, message):
        print(f"[LOG] {message}")

class DatabaseModel:
    def save(self):
        print("Saving to database")

class User(LoggerMixin, DatabaseModel):
    def save(self):
        self.log("Saving user")
        super().save()

The C3 Linearization Magic

Python uses the C3 linearization algorithm to create a consistent method resolution order. This ensures:

  • Each class appears exactly once
  • Subclasses come before their bases
  • The order respects the inheritance declaration

The beauty? You get predictable behavior even in complex hierarchies. The MRO isn't just "left-to-right" - it's a sophisticated algorithm that prevents ambiguity.

MRO Best Practices

  • Design with composition over inheritance when possible
  • Use mixins for adding behavior without complex hierarchies
  • Always check .__mro__ when debugging inheritance issues
  • Trust super() to follow the MRO correctly

Related Resources

Deepen your understanding with Python's super() function and explore Python's object-oriented patterns. For debugging complex hierarchies, check out Python's debugging tools.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Python