Calculate the C3 Method Resolution Order
Core idea
C3 linearization orders classes so a derived class precedes its bases and established precedence is preserved. To compute the order for C(B1, B2), start with C and merge the MROs of B1 and B2 plus the direct-base list [B1, B2]. Repeatedly choose the first list head that does not occur in any remaining list tail; remove that class from the heads where it appears. If no head qualifies while lists remain, the hierarchy is inconsistent.
class A: passclass B: passclass C(A, B): passprint([c.__name__ for c in C.mro()])Merge [A, object], [B, object], [A, B]: choose A, then B (object is still in a tail), then object.
Preserve an established order
class A: passclass B(A): passclass C(B, A): passprint([c.__name__ for c in C.mro()])B already precedes A. The direct bases agree, so the merge yields B, A, object.
Intentional failure: conflicting order
class A: passclass B: passclass Left(A, B): passclass Right(B, A): passclass Broken(Left, Right): passLeft requires A before B; Right requires B before A. After Left and Right there is no eligible head. Class creation fails.
Common mistake
C3 is not simply depth-first search. A shared base can be delayed to satisfy the ordering constraints of another branch.
Practice
Write the merge lists for the diamond in the previous lesson. Cross out eligible heads in order and compare your answer with mro().
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Calculate C3 linearization
Check your understanding of c3 mro.
What is printed?
class A: passclass B: passclass C(B, A): passprint([c.__name__ for c in C.mro()])What is printed?
class A: passclass L(A): passclass R(A): passclass C(L, R): passprint([c.__name__ for c in C.mro()])Which exception is raised by this intentionally inconsistent hierarchy?
class A: passclass B(A): passclass C(A, B): passWhen can a candidate head be selected in a C3 merge?