Advertisement
Advanced Python, Multiple Inheritance & MRO

Why does Python sometimes raise 'TypeError: Cannot create a consistent method resolution order'?

Short answer

This error occurs when the C3 linearization algorithm cannot find any ordering of base classes that satisfies all the required constraints simultaneously -- typically caused by listing base classes in an order that contradicts their own inheritance relationships, such as `class…

Save Python mock interview
Advertisement
AModel answer
This error occurs when the C3 linearization algorithm cannot find any ordering of base classes that satisfies all the required constraints simultaneously -- typically caused by listing base classes in an order that contradicts their own inheritance relationships, such as `class C(A, B)` where B is itself a subclass of A, making it impossible to place A before B (required by A being a base of B) while also respecting the declared order (A before B) without contradiction.
class A: pass
class B(A): pass

try:
    class C(A, B):  # A listed before B, but B already inherits from A
        pass
except TypeError as e:
    print(e)  # Cannot create a consistent MRO for bases A, B
Real-world example
A refactor accidentally reorders a class's base list, introducing this exact contradiction, and the resulting TypeError immediately flags the inheritance structure as invalid before any code even runs.
Likely follow-ups
  • How do you fix this specific error in the example?
  • What general rule avoids triggering this error?
Related topics