Skip to content

Python super(): Cooperative Inheritance and the MRO

  • What super() returns and where its search starts: the class after the current one in type(self).__mro__, not “my parent”.
  • Why calling parents by name breaks under multiple inheritance, and how super() runs each class exactly once.
  • The zero-argument and two-argument forms, and how super() works in class methods, properties and __init_subclass__.
  • How to design cooperative classes: matching signatures, **kwargs forwarding and a root class that ends the chain.
  • The failure modes: nested functions and generator expressions, assignment through super(), and unhelpful errors from leftover keywords.

super() returns a proxy that looks up attributes in the classes that come after the current class in the instance’s method resolution order (MRO). In single inheritance that is the parent; with multiple inheritance it can be a sibling the current class has never heard of. That is what lets a chain of mixins each run once. The zero-argument form arrived in Python 3.0 (PEP 3135) and super() is current in Python 3.14, where super objects also became copyable and picklable.

OrdersPortal’s model classes share a base and combine behaviors through multiple inheritance. When each class calls its parent by name, the shared base runs once per path through the hierarchy. 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.

before.py
class Model:
def __init__(self, record_id):
print(f"Model.__init__({record_id!r})")
self.record_id = record_id
class Timestamped(Model):
def __init__(self, record_id):
Model.__init__(self, record_id) # parent named explicitly
self.created_at = "2026-11-18T09:00:00Z"
class Audited(Model):
def __init__(self, record_id):
Model.__init__(self, record_id)
self.changes = []
class Order(Timestamped, Audited):
def __init__(self, record_id):
Timestamped.__init__(self, record_id)
Audited.__init__(self, record_id)
Order("ORD-1")
Model.__init__('ORD-1')
Model.__init__('ORD-1')

Model.__init__ runs twice. Here that only resets an attribute; in real code it might open a second connection, register the object twice or reset state the first path already set. Order also has to know about every parent and call them in the right order. With super():

after.py
class Model:
def __init__(self, record_id):
print(f"Model.__init__({record_id!r})")
self.record_id = record_id
class Timestamped(Model):
def __init__(self, record_id):
super().__init__(record_id) # "the next class in the MRO"
self.created_at = "2026-11-18T09:00:00Z"
class Audited(Model):
def __init__(self, record_id):
super().__init__(record_id)
self.changes = []
class Order(Timestamped, Audited):
pass # inherits Timestamped.__init__, which starts the chain
order = Order("ORD-1")
print([cls.__name__ for cls in Order.__mro__])
print(sorted(vars(order)))
Model.__init__('ORD-1')
['Order', 'Timestamped', 'Audited', 'Model', 'object']
['changes', 'created_at', 'record_id']

Timestamped’s super() call reaches Audited, not Model, because Audited comes next in Order’s MRO. Every initializer runs once, in MRO order.

super(type, object_or_type) searches object_or_type’s MRO, starting with the class right after type. Two inputs matter: the class where the call is written (where the search starts) and the class of the instance (which MRO is searched). The method resolution order page explains how the MRO is computed (C3 linearization).

  • Zero-argument form. Inside a method, super() means super(__class__, self). The compiler creates an implicit __class__ cell for any method that uses super or __class__, holding the class being defined; the instance is the method’s first argument. In a class method the first argument is cls, so super() searches cls.__mro__.
  • Two-argument form. super(Left, obj) works anywhere, including outside a class. If the second argument is an instance, isinstance(obj, Left) must be true; if it is a class, it must be a subclass (the class method case).
  • Explicit lookups only. super() customizes attribute lookup, so super().__getitem__(key) works but super()[key] raises TypeError: 'super' object is not subscriptable. Operators and len() look up special methods on the type and bypass the proxy.
  • Read, not write. super().total reads a parent’s property; super().total = 5 raises AttributeError. Call the parent’s setter explicitly if you need it.
  • Nested scopes. Zero-argument super() fails in a nested function (RuntimeError: super(): no arguments) and in a generator expression, which is a nested scope whose first argument is an iterator. Since Python 3.12, list, dict and set comprehensions are inlined (PEP 709), so super() inside them works.
how.py
class Base:
def describe(self):
return "Base"
class Left(Base):
def describe(self):
return "Left -> " + super().describe()
class Right(Base):
def describe(self):
return "Right -> " + super().describe()
class Both(Left, Right):
def describe(self):
return "Both -> " + super().describe()
# 1. super() in Left reaches Right: the search follows type(self).__mro__,
# starting after the class where super() is written.
print(Both().describe())
print(Left().describe())
# 2. The explicit two-argument form: start searching after Left in Both's MRO.
print(super(Left, Both()).describe())
# 3. Class methods use super() too; cls stays the subclass.
class Money:
@classmethod
def parse(cls, text):
return cls.__name__, text.strip()
class Eur(Money):
@classmethod
def parse(cls, text):
return super().parse(text.removesuffix("EUR"))
print(Eur.parse(" 12.50 EUR"))
# 4. Extending a read-only property.
class Order:
@property
def total_cents(self):
return 1000
class TaxedOrder(Order):
@property
def total_cents(self):
return super().total_cents * 120 // 100
print(TaxedOrder().total_cents)
# 5. Zero-argument super() needs the method's own frame.
class Broken(Base):
def describe(self):
return list(super().describe() for _ in range(1)) # generator expression = nested scope
try:
Broken().describe()
except TypeError as exc:
print("TypeError:", exc)
Both -> Left -> Right -> Base
Left -> Base
Right -> Base
('Eur', '12.50')
1200
TypeError: super(type, obj): obj (instance of range_iterator) is not an instance or subtype of type (Broken).

The same Left.describe code reaches Right for a Both instance and Base for a Left instance. A method that calls super() does not know which class runs next; that is decided by the subclass that combines it.

OrdersPortal’s repositories combine a storage base with validation and audit mixins. Each save does its own job and delegates the rest with super().save(). Each __init__ takes its own keyword-only arguments and forwards the rest, so classes can be combined in any order. Repository is the root: it is last before object, and its __init__ passes nothing extra to object.__init__. Class creation is cooperative too: __init_subclass__ consumes the entity class keyword and calls super().__init_subclass__(**kwargs). @typing.override (Python 3.12) asks type checkers to confirm the method really overrides something.

repositories.py
from typing import override
class Repository:
registry: dict[str, type["Repository"]] = {}
def __init_subclass__(cls, /, entity: str | None = None, **kwargs):
super().__init_subclass__(**kwargs) # keep the class-creation chain cooperative too
if entity is not None:
Repository.registry[entity] = cls
def __init__(self, **kwargs):
super().__init__(**kwargs) # object.__init__ rejects leftovers
self.rows: dict[str, dict] = {}
def save(self, record: dict) -> dict:
self.rows[record["id"]] = record
return record
class ValidationMixin:
required: tuple[str, ...] = ()
def __init__(self, *, strict: bool = True, **kwargs):
super().__init__(**kwargs) # take your own argument, pass the rest on
self.strict = strict
def save(self, record: dict) -> dict:
missing = [name for name in self.required if name not in record]
if missing and self.strict:
raise ValueError(f"missing fields: {missing}")
return super().save(record)
class AuditMixin:
def __init__(self, *, actor: str, **kwargs):
super().__init__(**kwargs)
self.actor = actor
self.audit_log: list[str] = []
def save(self, record: dict) -> dict:
saved = super().save(record)
self.audit_log.append(f"{self.actor} saved {saved['id']}")
return saved
class OrderRepository(AuditMixin, ValidationMixin, Repository, entity="order"):
required = ("id", "customer_id", "total_cents")
@override
def save(self, record: dict) -> dict:
return super().save({"status": "pending", **record})
print([cls.__name__ for cls in OrderRepository.__mro__])
print(Repository.registry)
repo = OrderRepository(actor="ops@example.test", strict=True)
repo.save({"id": "ORD-1001", "customer_id": "C-7", "total_cents": 2500})
print(repo.rows["ORD-1001"])
print(repo.audit_log)
try:
repo.save({"id": "ORD-1002", "customer_id": "C-7"})
except ValueError as exc:
print("ValueError:", exc)
print(repo.audit_log) # the failed save was never audited
try:
OrderRepository(actor="ops@example.test", stirct=False) # typo in a keyword
except TypeError as exc:
print("TypeError:", exc)
['OrderRepository', 'AuditMixin', 'ValidationMixin', 'Repository', 'object']
{'order': <class '__main__.OrderRepository'>}
{'status': 'pending', 'id': 'ORD-1001', 'customer_id': 'C-7', 'total_cents': 2500}
['ops@example.test saved ORD-1001']
ValueError: missing fields: ['total_cents']
['ops@example.test saved ORD-1001']
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

The order of the bases is a design decision: AuditMixin comes first, so it wraps validation and only audits saves that succeeded. Swap the two mixins and every attempt would be audited. The last line shows the cost of **kwargs forwarding: a misspelled keyword travels to object.__init__, and the error does not name it. Keep keyword names consistent and test construction.

  • Treating super() as “my parent”. In a mixin, super() may reach a sibling. Write every cooperative method so it works whatever class comes next.
  • Breaking the chain. One class in the hierarchy that forgets super().__init__(...) silently skips every class after it in the MRO.
  • Mismatched signatures. If Timestamped.__init__(self, record_id) and Audited.__init__(self, record_id, actor) both call super(), one of them receives the wrong arguments. Use the same signature or keyword-only arguments plus **kwargs.
  • Mixing super() and explicit Base.method(self) calls. One explicit call in the chain reintroduces double execution or skipped classes.
  • No root class. If two mixins both forward save to super() and no class implements it, you get AttributeError: 'super' object has no attribute 'save'. Put a terminating implementation in a common base.
  • Zero-argument super() in a nested function or generator expression. Pass explicit arguments or compute the value in the method body first.
  • Assigning through super(). super().attr = value raises AttributeError; to call a parent’s property setter, use Parent.attr.fset(self, value).
Situation Approach
Single inheritance, extending a parent method super().method(...)
Mixins that each add behavior to the same method Cooperative super() in every class, plus a root class
Different signatures you cannot change (third-party classes) Adapter class that calls the third-party class explicitly
You need to call one specific ancestor and skip others Explicit Ancestor.method(self), documented; usually a design smell
Behavior combined from independent parts Composition: hold the parts as attributes instead of inheriting

Zero-argument super() and the implicit __class__ cell exist in every Python 3 release (PEP 3135, Python 3.0). Python 3.6 added __init_subclass__ and the __classcell__ hand-off to metaclasses. Python 3.12 added the LOAD_SUPER_ATTR instruction, which speeds up super() attribute access, inlined comprehensions (PEP 709), and typing.override (PEP 698). Python 3.14 made super objects copyable and picklable.

1. In class Order(Timestamped, Audited), both bases inherit from Model and use super().__init__(). Which class does Timestamped’s call reach? Audited. The search uses Order.__mro__ (Order, Timestamped, Audited, Model, object) and starts after Timestamped. For a plain Timestamped instance, the same call reaches Model.

2. How does zero-argument super() know the class and the instance? The compiler gives every method that uses super or __class__ an implicit __class__ closure cell pointing at the class being defined, and super() takes the first argument of the current frame as the instance (or class, in a class method). That is why it fails in nested functions and generator expressions.

3. Why do cooperative __init__ methods usually take keyword arguments and **kwargs? A class cannot know which class comes next in the MRO, so it cannot know that class’s positional parameters. Each class takes its own keyword arguments and forwards the rest; the root passes nothing to object.__init__, which rejects extra arguments.

4. Senior scenario: OrdersPortal adds CachingMixin to OrderRepository, and saved orders sometimes skip validation. How do you diagnose and fix it? Print OrderRepository.__mro__ and read every save in that order. The likely cause is a class that does not call super().save() on some path (for example a cache hit returning early before delegating) or a base order that puts the cache before validation. Decide the intended layering explicitly (audit, then validation, then cache, then storage), order the bases to match, make every save delegate on every path, and add a test that asserts the MRO and one that proves an invalid record is rejected even when cached. If the layering keeps changing, replace the mixins with composition: a pipeline of explicit steps is easier to reason about.

  • super() continues the search in type(self).__mro__ after the class where it is written; it can reach a sibling.
  • Use it consistently so each class in a diamond runs exactly once.
  • Cooperative methods need compatible signatures, keyword arguments with **kwargs forwarding, and a root class that ends the chain.
  • Zero-argument super() relies on the __class__ cell and the method’s first argument; it does not work in nested functions or generator expressions.
  • Base-class order is behavior: reorder mixins deliberately and test the result.