Inheritance
Method Resolution Order (MRO)
C3 linearization and how Python resolves method lookups
Interview: Advanced Python — tests understanding of MRO algorithm, diamond problem resolution, and super() behavior
The Method Resolution Order (MRO) determines the order in which Python searches for methods in a class hierarchy. It uses the C3 linearization algorithm to produce a consistent, predictable ordering that handles multiple inheritance correctly. Understanding MRO is crucial for debugging complex inheritance hierarchies.
C3 Linearization Rules
- Children before parents: A class is always searched before its parents
- Left to right: If a class has multiple parents, they're searched in declaration order
- Monotonicity: A class always appears after its parents in any subclass's MRO
- If no consistent order exists, Python raises
TypeError
Inspecting MRO
Use ClassName.__mro__ (tuple) or ClassName.mro() (list) to see the resolution order. This is invaluable for debugging complex inheritance hierarchies.
Common Pitfall
If you create a class hierarchy where C3 can't find a consistent order, Python raises TypeError: Cannot create a consistent method resolution. This usually means your inheritance graph has conflicting constraints.
Use Cases
Debugging complex inheritance hierarchies to understand method dispatch
Designing mixin-based frameworks (Django views, Flask blueprints)
Understanding super() behavior in cooperative multiple inheritance
Detecting and fixing MRO conflicts in class hierarchies
Building plugin architectures where method resolution order matters
Common Mistakes
Creating diamond hierarchies with conflicting ordering (TypeError)
Not checking __mro__ when debugging unexpected method behavior
Assuming super() always calls the direct parent (it follows MRO)
Forgetting that object is always at the end of MRO
Designing overly complex hierarchies where MRO becomes unpredictable