Skip to content

Python Method Resolution Order (MRO) and C3

  • What the method resolution order is and where Python uses it.
  • How C3 linearization computes __mro__, by hand and in a few lines of Python.
  • Why some hierarchies are rejected with “Cannot create a consistent method resolution order”.
  • How super() follows the MRO, and how to write cooperative mixins that rely on it.
  • How to explain MRO behavior in an interview.

The method resolution order (MRO) is the ordered list of classes Python searches when it looks up an attribute on a class or its instances. Every class stores it as the tuple __mro__, and type.mro() computes it. Python uses the C3 linearization algorithm, introduced in Python 2.3 and unchanged in Python 3.14. C3 guarantees that a class comes before its bases, that bases keep the order you listed them in, and that the order is consistent across subclasses. super() uses the same order, which is what makes cooperative multiple inheritance work.

With multiple inheritance, more than one ancestor can define the same method, and ancestors can be shared. In the OrdersPortal app, an OrderRepository combines an audit mixin and a cache mixin, both built on Repository: a diamond. Python must decide which save() runs, and in what order the chain continues, so that each class runs exactly once.

The samples on this page are plain scripts: save each as a .py file and run it with python3 file.py. They were run on CPython 3.14.6 and the output shown is from that run.

class Repository:
def save(self, order):
return ["Repository.save"]
class AuditMixin(Repository):
def save(self, order):
return ["AuditMixin"] + super().save(order)
class CacheMixin(Repository):
def save(self, order):
return ["CacheMixin"] + super().save(order)
class OrderRepository(AuditMixin, CacheMixin):
def save(self, order):
return ["OrderRepository"] + super().save(order)
print([c.__name__ for c in OrderRepository.__mro__])
print(OrderRepository().save("ORD-1001"))
# Calling parents by name bypasses the MRO: Repository.save runs twice.
class AuditMixinV1(Repository):
def save(self, order):
return ["AuditMixinV1"] + Repository.save(self, order)
class CacheMixinV1(Repository):
def save(self, order):
return ["CacheMixinV1"] + Repository.save(self, order)
class OrderRepositoryV1(AuditMixinV1, CacheMixinV1):
def save(self, order):
return (["OrderRepositoryV1"] + AuditMixinV1.save(self, order)
+ CacheMixinV1.save(self, order))
print(OrderRepositoryV1().save("ORD-1001"))

Output:

['OrderRepository', 'AuditMixin', 'CacheMixin', 'Repository', 'object']
['OrderRepository', 'AuditMixin', 'CacheMixin', 'Repository.save']
['OrderRepositoryV1', 'AuditMixinV1', 'Repository.save', 'CacheMixinV1', 'Repository.save']

With super(), each class hands off to the next class in the MRO of the instance’s type, so AuditMixin continues to CacheMixin, not to its own base Repository, and Repository.save runs once. Calling parents by name, as the V1 classes do, ignores the MRO: the shared base runs twice. Python’s old depth-first, left-to-right order for classic classes had a related flaw: for this diamond it would search Repository before CacheMixin, so a method overridden in CacheMixin could be shadowed by the shared base.

For a class C with bases B1 ... BN, the linearization is:

L[C] = C + merge(L[B1], ..., L[BN], [B1, ..., BN])

The merge repeatedly takes the first good head: the first element of a list that does not appear in the tail (any position but the first) of another list. It appends that class to the result, removes it from every list, and starts again. If no list has a good head, there is no consistent order and class creation fails.

Here it is as a short teaching implementation, checked against the real mro():

def c3_linearize(cls):
"""Pure-Python C3, for teaching: L[C] = C + merge(L[B1]..L[Bn], [B1..Bn])."""
bases = list(cls.__bases__)
seqs = [c3_linearize(b) for b in bases] + [bases]
result = [cls]
while True:
seqs = [s for s in seqs if s]
if not seqs:
return result
for seq in seqs: # find a "good head"
head = seq[0]
if not any(head in s[1:] for s in seqs):
break
else:
raise TypeError("no consistent MRO")
result.append(head)
seqs = [s[1:] if s[0] is head else s for s in seqs]
class Entity: pass
class Timestamped(Entity): pass
class SoftDeletable(Entity): pass
class Auditable(Timestamped): pass
class Order(Auditable, SoftDeletable): pass
names = lambda seq: [c.__name__ for c in seq]
print(names(c3_linearize(Order)))
print(names(Order.mro()))
print(c3_linearize(Order) == Order.mro())
# An ordering conflict has no linearization.
class A: pass
class B: pass
class AB(A, B): pass
class BA(B, A): pass
try:
class Broken(AB, BA): pass
except TypeError as exc:
print("TypeError:", exc)
# A base listed before its own subclass is also rejected.
try:
class Bad(Entity, Timestamped): pass
except TypeError as exc:
print("TypeError:", exc)

Output:

['Order', 'Auditable', 'Timestamped', 'SoftDeletable', 'Entity', 'object']
['Order', 'Auditable', 'Timestamped', 'SoftDeletable', 'Entity', 'object']
True
TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B
TypeError: Cannot create a consistent method resolution order (MRO) for bases Entity, Timestamped

Worked by hand for Order(Auditable, SoftDeletable):

  1. L[Auditable] = [Auditable, Timestamped, Entity, object] and L[SoftDeletable] = [SoftDeletable, Entity, object].
  2. Merge those with the base list [Auditable, SoftDeletable]. Auditable is a good head: take it. Timestamped is next and appears in no tail: take it.
  3. Entity is now a head, but it is still in the tail of [SoftDeletable, Entity, object], so skip it. SoftDeletable is a good head: take it.
  4. Then Entity, then object.

The result keeps Timestamped close to Auditable (it is only reachable through it) but delays the shared Entity until every class that inherits from it has been listed.

The two failures in the sample are typical:

  • Conflicting local orders. AB says A before B and BA says B before A. No list can satisfy both, so class Broken(AB, BA) fails.
  • A base listed before its own subclass. class Bad(Entity, Timestamped) asks for Entity before Timestamped, but Timestamped must precede its base. Drop Entity, which is already inherited, or list the subclass first.

The error is raised when the class statement runs, never later at call time.

  • Attribute lookup on instances and classes walks type(obj).__mro__, for methods and plain class attributes alike. Data descriptors such as properties found in the MRO take precedence over the instance __dict__.
  • super() returns a proxy that searches the MRO of type(self) (or of cls) starting after the class in which the method is defined. super(Class, obj) makes the starting point explicit.
  • __init_subclass__ is called on the next class in the new class’s MRO.
  • isinstance() and issubclass() consult the MRO for ordinary classes, though ABCs can extend them.

ClassName.__mro__ is a read-only tuple; ClassName.mro() returns a list and is the method a metaclass may override, which is very rarely a good idea. inspect.getmro(cls) returns the same tuple.

OrdersPortal’s services are assembled from mixins: one adds retries, another records metrics, and the concrete RefundService adds its own settings. Each __init__ takes the keyword arguments it understands and passes the rest along with super().__init__(**kwargs). A root class at the end of the chain rejects leftovers, so a misspelled option fails instead of being silently dropped.

class Service:
"""Root of the cooperative chain: accepts and swallows nothing."""
def __init__(self, **kwargs):
if kwargs:
raise TypeError(f"unexpected options: {sorted(kwargs)}")
super().__init__()
self.log = []
def handle(self, order_id):
self.log.append(f"handled {order_id}")
return self.log
class RetryMixin(Service):
def __init__(self, *, retries=3, **kwargs):
super().__init__(**kwargs) # pass the rest along the MRO
self.retries = retries
def handle(self, order_id):
self.log.append(f"retry<= {self.retries}")
return super().handle(order_id)
class MetricsMixin(Service):
def __init__(self, *, metric_prefix="orders", **kwargs):
super().__init__(**kwargs)
self.metric_prefix = metric_prefix
def handle(self, order_id):
self.log.append(f"metric {self.metric_prefix}.handle")
return super().handle(order_id)
class RefundService(RetryMixin, MetricsMixin):
def __init__(self, *, max_amount, **kwargs):
super().__init__(**kwargs)
self.max_amount = max_amount
print([c.__name__ for c in RefundService.__mro__])
svc = RefundService(max_amount=500, retries=5, metric_prefix="refunds")
print(svc.handle("ORD-1001"))
try:
RefundService(max_amount=500, retrys=5)
except TypeError as exc:
print("TypeError:", exc)
# The same mixin, a different "next class": super() depends on type(self).
class PlainRetryService(RetryMixin):
pass
print([c.__name__ for c in PlainRetryService.__mro__])
print(PlainRetryService().handle("ORD-2002"))
# super(Class, obj) starts the search *after* Class in type(obj).__mro__.
print(super(RetryMixin, svc).handle.__qualname__)

Output:

['RefundService', 'RetryMixin', 'MetricsMixin', 'Service', 'object']
['retry<= 5', 'metric refunds.handle', 'handled ORD-1001']
TypeError: unexpected options: ['retrys']
['PlainRetryService', 'RetryMixin', 'Service', 'object']
['retry<= 3', 'handled ORD-2002']
MetricsMixin.handle

Three points from the output:

  • The same RetryMixin.handle continues to MetricsMixin inside RefundService but straight to Service inside PlainRetryService. super() means “next in this instance’s MRO”, not “my parent”.
  • Keyword-only arguments plus **kwargs keep the signatures compatible whatever order the mixins end up in. Positional arguments do not survive reordering.
  • super(RetryMixin, svc) starts searching after RetryMixin in RefundService.__mro__, so it finds MetricsMixin.handle.
  • Calling a parent by name in a cooperative hierarchy. Repository.save(self, ...) skips the rest of the MRO and can run a shared base twice. Use super() in every class of the chain.

  • One class in the chain not calling super(). The chain stops there, and every class after it in the MRO is silently skipped.

  • Incompatible __init__ signatures. If one mixin’s __init__ takes positional arguments and another does not, the order of bases decides which call breaks. Use keyword-only arguments and forward **kwargs.

  • Listing a base before its own subclass. class X(Base, Derived) cannot be linearized; remove the redundant base.

  • Assuming the MRO is depth-first. Shared bases come after all of their subclasses, as Entity did above.

  • Putting a mixin after the class it should wrap. With a plain mixin (one that does not inherit from Service), class Wrong(Service, RetryMixin) puts Service.handle first; it does not call super(), so the mixin never runs. Mixins go to the left:

    class Service:
    def handle(self, order_id):
    return [f"handled {order_id}"]
    class RetryMixin: # a plain mixin, not derived from Service
    def handle(self, order_id):
    return ["retry"] + super().handle(order_id)
    class Wrong(Service, RetryMixin): pass
    class Right(RetryMixin, Service): pass
    print(Wrong().handle("ORD-1"), Right().handle("ORD-1"))
    ['handled ORD-1'] ['retry', 'handled ORD-1']
Design Use when Watch out for
Single inheritance One clear “is-a” relationship Deep chains become hard to follow
Cooperative mixins with super() Small, orthogonal behaviors (retry, metrics, audit) shared by many classes Every class must call super() and accept **kwargs
Composition (holding helper objects) Behaviors with their own state, or that vary at runtime More wiring code, but explicit
Protocols / ABCs Defining an interface without sharing implementation No code reuse by themselves

If you need to print __mro__ to understand which method runs, the hierarchy is probably too clever; prefer composition.

All Python 3 classes are new-style and use C3. Python 2.2 introduced new-style classes with a different, non-monotonic order, Python 2.3 switched them to C3, and classic classes in Python 2 kept a depth-first, left-to-right search. Zero-argument super() arrived in Python 3.0 (PEP 3135). Nothing about the MRO algorithm changed in Python 3.14.

1. What is D.__mro__ for class D(B, C) where B and C both inherit from A? (D, B, C, A, object). B comes before C because of the base list order, and A comes after both because every class must precede its bases.

2. Why does super() in a mixin sometimes call a class that is not the mixin’s base? super() searches the MRO of the instance’s actual type, starting after the current class. In RefundService, the class after RetryMixin is MetricsMixin, even though RetryMixin only inherits from Service.

3. Give an example of a hierarchy Python rejects, and explain why. class AB(A, B), class BA(B, A), then class C(AB, BA). C3 must keep A before B for AB and B before A for BA; no order satisfies both, so a TypeError is raised when C is defined.

4. Senior scenario: an OrdersPortal class inherits from five mixins, some call super() and some call parents by name, and a recent base reordering made audit logging run twice and caching stop. How do you fix it and prevent recurrences? Print __mro__ to see the actual chain, then make every participating method cooperative: call super() everywhere, use keyword-only parameters and forward **kwargs, and end the chain in a root class that does not call super() for that method and rejects unexpected arguments. Add a test that asserts the expected __mro__ and a test that each mixin’s effect happens exactly once. Then question the design: behaviors with their own state, such as caching, usually work better as composed collaborators than as mixins, which removes the ordering dependency entirely.

  • The MRO is the lookup order for attributes; read it with __mro__ or mro().
  • Python 3 uses C3: a class before its bases, bases in the listed order, shared bases after all their subclasses.
  • Inconsistent hierarchies fail with TypeError when the class is defined.
  • super() continues in the MRO of the instance’s type, which makes cooperative mixins possible.
  • Cooperative methods need super() in every class and keyword arguments forwarded with **kwargs.