This rule raises an issue when a class definition with multiple inheritance results in an unresolvable Method Resolution Order (MRO).
Python uses the C3 linearization algorithm (also called C3 superclass linearization) to determine the Method Resolution Order (MRO) - the order in which base classes are searched when looking up methods and attributes. This algorithm ensures a consistent and predictable class hierarchy.
When a class is created with multiple inheritance, Python must be able to construct a valid MRO. If the inheritance structure violates the C3
linearization rules, Python raises a TypeError at class definition time, preventing the class from being created at all.
The C3 algorithm enforces these key constraints:
C inherits from A then B (i.e., class C(A,
B)), then A must appear before B in the MROA appears before class B in the MRO of a parent class, then A
must also appear before B in the MRO of any child classViolating these rules creates an inconsistent hierarchy where Python cannot determine which parent class should take precedence.
MRO inconsistencies cause immediate failures at class definition time — Python raises a TypeError and the class is never created,
breaking the application at import time.
To fix MRO inconsistencies, restructure the inheritance hierarchy to respect the C3 linearization rules. Remove redundant base classes from the inheritance list, as a class does not need to directly inherit from a grandparent if it is already inherited through a parent.
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, A, C): # Noncompliant: inconsistent MRO for bases A and C; D requires A before C, but C inherits from A
pass
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C): # Compliant: A is inherited through B and C
pass
__mro__
attribute