What class actually does, how __new__ differs from __init__, and why super() is not “call the parent”. That last one breaks more code than any other mistake in this lesson.
class B:
def __new__(cls): return 42
def __init__(self): print("init")
print(B())
42The init line was not printed. The constructor returned a number.class X: pass
class Y(X): pass
class Z(X): pass
class W(Y, Z): pass
print([c.__name__ for c in W.__mro__])
class Bad(X, Y): pass
['W', 'Y', 'Z', 'X', 'object']
TypeError: Cannot create a consistent method resolution
order (MRO) for bases X, YAn error at class declaration, before any call at all.class Base:
def setup(self): print("Base")
class Log(Base):
def setup(self): print("Log"); super().setup()
class Cache(Base):
def setup(self): print("Cache") # forgot super()
class Svc(Log, Cache):
def setup(self): print("Svc"); super().setup()
Svc().setup()
Svc
Log
CacheWhere is Base? It is in the MRO, it has setup, and it did not run.class Registry:
items = [] # a class attribute
a = Registry(); b = Registry()
a.items.append(1)
print(b.items)
[1]Two different objects, one list.class is an executable statement, just like def. The class body is executed as an ordinary block of code in its own namespace; the resulting dictionary of names is passed to the type's constructor, which creates the class object.
Creating an instance takes two steps. __new__ creates the object and returns it; __init__ receives the already-created object and sets it up.
The lookup order in a hierarchy is given by the MRO linearization, computed once when the class is created.
Snippet D is explained straight from this plus lesson 01. The line items = [] is executed once, when the class is created, and creates one list, which becomes an attribute of the class. Instances do not get a list of their own — they see the class one through step 3 of the procedure from lesson 04.
This is the same mistake as the shared mutable default argument, in different clothes: in both cases the expression is evaluated once, at the moment the declaration executes. One understanding closes both cases, and there is no need to memorize them separately.
It also follows that a class body can contain any code — loops, conditions, computations — and that a class decorator receives an already-finished object.
__new__ creates, __init__ sets upCalling B() is not a single operation. The type calls __new__, gets an object, and only if the result is an instance of this class calls __init__ on it.
Snippet A: __new__ returned a number, the check failed, __init__ was not called. No error — the language considers this legitimate.
From this you can derive when each method is needed. __init__ — almost always: the object exists, the fields need filling in. __new__ — only when the object cannot be set up after creation: immutable types (str and tuple simply have no “after”), caching of instances, substituting the class that is returned. And a consequence that explains a common mistake: __init__ cannot return anything — if it returns something other than None, you get a TypeError.
Inheritance defines an “ancestor — descendant” relation on classes. With multiple inheritance this relation is partial: about Y and Z you cannot say which comes first. C3 linearization builds a linear order from it with three properties: each class exactly once, a descendant strictly before any ancestor, and the order of base classes from the declaration is preserved.
Snippet B: for W(Y, Z) you get W, Y, Z, X, object — X has to come after both descendants. And for Bad(X, Y) no order exists: the declaration requires X before Y, and inheritance requires Y before X. A contradiction, and Python reports it when the class is created, not when a method is called.
This is a rare case, for a dynamic language, of an error caught as early as possible — and it is possible precisely because the linearization is computed once, not on every access.
super() is not the parentHere is a definition worth keeping in your head word for word: super() hands control to the next class in the MRO of the object on which the call is made. Not the parent of the class where the line is written. Not the first base. The next one in the linearization of the specific instance.
Snippet C shows how this differs in practice. The MRO of Svc is Svc, Log, Cache, Base, object. The call goes: Svc.setup → super() → Log.setup → super() → Cache.setup. Note: Cache is not an ancestor of Log at all; they are siblings in the hierarchy. And Log knows nothing about the existence of Cache — it simply passed control further down the chain.
And Cache.setup did not call super() — so the chain broke. Base.setup did not run, although it is next in the MRO. No error, no exception; part of the logic just silently did not happen.
Hence the rule of cooperative inheritance, which otherwise looks like superstition: if a method is overridden in a class that takes part in multiple inheritance, it must call super() — even if it has no “parent” in the intuitive sense. One omission in the middle of the chain switches off everything that comes after it.
super() without arguments works only inside a class body. The compiler puts a hidden reference to the class there — hence the __class__ variable in the method's closure. Outside a class body you need the full form super(Cls, obj), and in dynamically created methods this comes up regularly.
Cooperation requires compatible signatures. If the classes in the chain accept different sets of arguments, super() has no one to pass them to — hence the convention of accepting **kwargs and passing them on. This is a discipline, not a mechanism: the language does not check it.
Class creation can be intercepted. A metaclass, __init_subclass__ and __set_name__ wedge themselves into the moment described in consequence 1 — lesson 07 is devoted to this. For now it is enough to know that the extension point is there.
The root is the same R2: everything is resolved at runtime. A class is an ordinary object created by executing code, its dictionary can be changed after creation, and the lookup order is computed and stored as data rather than baked into the compiler.
This construction appeared in 2001, when Guido was unifying types and classes. Before that, Python had two kinds of classes with different rules, and the MRO of the old ones was computed by a depth-first, left-to-right traversal — because of which, in a diamond, the common ancestor was visited before the second descendant, and cooperative inheritance was impossible. C3 was taken from Dylan; together with it came descriptors, property and super() — the whole mechanism of lesson 04 and of this lesson was born from one decision.
For a mathematician the formulation is exact: the MRO is a topological sort of the directed acyclic inheritance graph, with the additional requirement of preserving the local order of base classes in each declaration. C3 is a specific merge algorithm that yields such a sort if it exists and reports a failure if it does not.
This immediately shows why Bad(X, Y) is not created: the edges added by the declaration form a cycle, and a graph with a cycle has no topological sort. And it shows why the error arises at declaration: the sort is computed once, at that very moment.
Questions that come up on their own if you read closely. The answer is under the question.
__new__, if there is __init__?Because __init__ receives an already-created object and cannot decide what it will be.
The division is simple: __new__ is the constructor — it creates the object and returns it; __init__ is the initializer — it sets up the object it receives and must return None.
As long as the class is mutable and ordinary, the difference is invisible. It becomes fundamental in two cases.
Immutable types. For tuple, str, int and frozenset the value is set at creation and never changes again — there is nothing to set up in __init__:
class Point(tuple):
def __new__(cls, x, y):
return super().__new__(cls, (x, y)) # the only place where the contents can be set
p = Point(1, 2)
print(p, p[0]) # → (1, 2) 1
Returning someone else's object. __new__ can return something other than a new instance — singletons, object caches and factories that choose a subclass based on data rest on this. A subtlety: if __new__ returned an object not of this class, __init__ will not be called at all.
In practice: application code rarely needs __new__, and people almost always reach for it in vain — for a “singleton” a module-level variable is usually enough, for a factory a classmethod with a clear name. But when inheriting from an immutable built-in type there is no way around it.
super() without arguments know which class it is in?The compiler writes it a hint — this is not runtime magic but a decision made at compile time.
If super appears in a method body, the compiler adds a hidden free variable __class__ to the function, pointing at the class in which the method is defined. You can see it directly:
class A:
def m(self): return super()
print(A.m.__code__.co_freevars) # → ('__class__',)
class B:
def m(self): return 1
print(B.m.__code__.co_freevars) # → () no hint
Then super() takes __class__ and the first positional argument (that is, self) and turns into super(__class__, self).
Hence all the restrictions that seem arbitrary. Outside a class body super() without arguments does not work — there is nowhere to get the hint from. In a staticmethod it does not work — there is no first argument. In a nested function inside a method it works, because the cell is captured by the closure. And if a method was attached to a class from outside after it was created, you will have to write the full form.
And the main thing to take away: super() goes not to the parent but to the next class in the MRO of the instance. For single inheritance that is the same thing, for multiple inheritance it is not, and that is exactly why cooperative inheritance works only when every participant in the chain observes it.
Because the ban in Java gave birth to interfaces, and then to default methods in interfaces — that is, to multiple inheritance coming in through another door.
The problem that makes people fear it is the “diamond”: a class inherits from two that share an ancestor, and it is unclear whose method to call. Python solves it with the C3 linearization algorithm: it builds one linear order in which each class appears exactly once, a descendant always comes before an ancestor, and the order of the base classes is preserved. If no such order exists, the class is simply not created:
class X: pass
class Y(X): pass
class Ok(Y, X): pass # descendant before ancestor — an order exists
print([c.__name__ for c in Ok.__mro__])
# → ['Ok', 'Y', 'X', 'object']
class Bad(X, Y): pass # ancestor before descendant — a contradiction
# → TypeError: Cannot create a consistent method resolution order (MRO)
An error at class creation, not at method call — that is the very guarantee the algorithm was chosen for.
In practice multiple inheritance in Python lives in one form — the mixin: a small class with no state of its own that adds behaviour. socketserver.ThreadingMixIn, collections.abc, half of Django. It works and it reads well.
What does not work: inheriting from two full-fledged classes with their own state and their own __init__. Here super() requires every participant in the chain to call super().__init__() and accept **kwargs, and if one of them breaks the rule the chain silently snaps. The rule: if both parents hold data, it is composition, not inheritance.
isinstance better than type(x) == C?Because the second breaks on subclasses — and on classes that pretend.
type(x) == C requires an exact match. A subclass, which must work everywhere the parent does, fails the check — a direct violation of the substitution principle:
class Money(int): pass
m = Money(5)
print(type(m) == int) # → False
print(isinstance(m, int)) # → True
The second difference is subtler: isinstance goes through the metaclass's __instancecheck__, and that is an extension point. The ABCs of lesson 11 rest on it — isinstance(x, collections.abc.Iterable) works for any class with __iter__, with no inheritance at all. And typing.Protocol with runtime_checkable rests on it too.
Where type(x) is C is appropriate after all: when precision is the goal — a serializer that must tell bool from int (and bool is a subclass of int, so isinstance(True, int) is true), dispatch on a concrete type, a debugging check. In such cases you write is, not ==: types are singletons.
And the most common right answer is not to check the type at all. Lesson 11: if you need “this is a sequence”, ask about the protocol, not the class.
class is an executable statement: the body runs as code, and the collected dictionary of names is passed to the type's constructor. Hence the shared mutable class attribute — the same mechanism as the shared default argument. Creating an instance goes in two steps: __new__ creates and returns, __init__ sets up — and is called only if __new__ returned an instance of this class. The lookup order is given by C3 linearization, that is, a topological sort of the inheritance graph: it is computed once at declaration, and if no compatible order exists the class is not created at all. And the main thing: super() hands control to the next class in the MRO of the specific object, not to the parent — that is why it links classes that know nothing about each other, and why one missing super() in the middle of the chain silently switches off everything after it.
Java and C# banned multiple inheritance of implementation and kept interfaces. The MRO problem does not exist, because the situation that creates it does not exist. The price is that mixins have to be assembled by composition and delegation by hand.
C++ allowed multiple inheritance and chose not to linearize: a common ancestor is duplicated unless declared virtual, and the programmer sets the order of calls. More control, more ways to get it wrong.
Ruby chose a third path: single inheritance plus mixin modules that are inserted into the lookup chain. That is effectively a linearization, only assembled by explicit includes instead of being computed from the graph.
Three answers to one question: “what to do when behaviour comes from several places”. Python alone computes the answer with an algorithm and refuses to create the class if there is no answer.
A mixin was added to the hierarchy — and part of the initialization stopped running. Silently.
class Service:
def __init__(self, **kw):
self.conn = connect()
super().__init__(**kw)
class WithMetrics(Service):
def __init__(self, **kw):
self.metrics = Metrics()
super().__init__(**kw)
class WithCache(Service):
def __init__(self, **kw):
self.cache = {} # forgot super()
class Api(WithMetrics, WithCache):
pass
The reviewer looks at WithCache on its own: the class inherits from Service, sets up its cache, everything is logical. In isolation it even works — if you create WithCache() directly, Service.__init__ will be called, because WithCache is next in its own MRO... no, it will not be called. And that is the first thing worth checking for yourself.
And in Api the chain breaks at WithCache, and self.conn is never created. The failure happens later and in another place — on the first access to the connection, with an AttributeError that looks like “forgot to initialize” and leads the investigation the wrong way.
Why review lets it through: the diff shows one added class, while what broke is a chain that is not in the diff. What needs checking is not the class but the MRO of the result:
print([c.__name__ for c in Api.__mro__])
# → ['Api', 'WithMetrics', 'WithCache', 'Service', 'object']
The rule derived from consequence 4: in a hierarchy with multiple inheritance every overridden method must call super(), even when it seems there is no one to call. And pass **kwargs on — otherwise the chain will break on mismatched signatures.
Untangling multiple inheritance from the sources takes hours. Asking the language takes a second.
[c.__name__ for c in SomeClass.__mro__]
SomeClass.method.__qualname__ # whose method actually won
import inspect
inspect.getmro(SomeClass)
inspect.getsource(SomeClass.method) # and its source
The linearization is data stored in the class object, not a result inferred from code. So any question “where did this method come from” and “in what order will the calls go” has an exact answer that does not need to be reconstructed.
The practical order when taking apart someone else's hierarchy: first __mro__ — see the real chain; then the __qualname__ of the method in question — understand whose implementation is active; then getsource — read exactly that one, not the one a search by name turned up. Three lines instead of reading five files, and the answer is guaranteed to be right, because it is the same thing the interpreter uses.
The same technique also closes the reverse question — “why is my method not called”: if the class sits in the MRO after whoever broke the chain, the answer is visible at once.
Run the four snippets and check them against your prediction. Then:
class A:
def __init__(self): print("A"); super().__init__()
class B:
def __init__(self): print("B"); super().__init__()
class C(A, B): pass
C()
# Why is B printed, although A and B are not related by inheritance?
class D(dict):
def __init__(self): self["x"] = 1
D()
# It works without calling super().__init__(). Why?
# And for a class inheriting from tuple it will not — why?
class E:
x = [1]
e = E(); e.x = e.x + [2]
E.x
# And if you write e.x += [2]? A different result — explain it through lesson 01.
# Without code: why does an MRO error arise when the class is declared,
# while a “no such attribute” error arises only on access?
The first question is the key one: it shows that super() links classes that know nothing about each other, and that cooperation works precisely thanks to the linearization.
Lib/enum.py, the EnumType.__new__ method. Consequence 1 is used to the full here: the body of an enumeration class is executed as ordinary code, all the names are collected into a dictionary, and then the type's constructor turns them into member objects of the enumeration.
Notice why the order of members is preserved: the namespace of a class body is a dictionary, and dictionaries have been insertion-ordered since 3.7 (lesson 05). Before that guarantee enum had to slip in a special dictionary type through __prepare__. One lesson rests on another literally in the code of the standard library.
The second place is Lib/socketserver.py. There classes such as ThreadingTCPServer are assembled from mixins by multiple inheritance, and you can see a live cooperative super() — exactly the construction that snippet C breaks.
From L1 you know that the class body is executed and the MRO is computed once. Here: the sequence and the cost.
The full order of class creation: the compiler turns the body into a separate code object; when class executes, that code runs in a fresh dictionary; the metaclass is determined (from the metaclass argument or as the most derived among the metaclasses of the bases); its __prepare__ is called, returning the dictionary for the body; the body runs; the metaclass is called with the name, the tuple of bases and the filled dictionary; inside, the MRO is computed, the type slots are set, __set_name__ is called on descriptors and __init_subclass__ on the nearest ancestor.
The result of the linearization is stored in the type object itself and available as __mro__. It is immutable: you cannot assign your own tuple there. But it is recomputed when __bases__ changes — and with that the type's version is bumped, invalidating the inline caches from lesson 04. Hence a practical effect: editing the hierarchy dynamically in hot code costs not only the edit itself but the loss of all specialization.
print(W.__mro__)
# → (<class 'W'>, <class 'Y'>, <class 'Z'>, <class 'X'>, <class 'object'>)
W.__mro__ = (...)
# → AttributeError: readonly attribute
About super() without arguments: when the compiler meets it in a method body, it adds a __class__ cell to the closure. It is easy to check — such a method gets a __closure__ that an ordinary one does not have. Hence the rule from section 3: outside a class body there is no cell, and the argument-less form does not work.
Tag v3.11.15.
Objects/typeobject.c, mro_implementation and pmerge — the whole of C3. The merge takes a page and reads easily if you remember the topological-sort formulation.type_new — the whole sequence of class creation from the L2 section, step by step.Objects/typeobject.c, super_getattro — how super() finds the next class: it takes the MRO of the object's type and goes from the position of its own class, not from the beginning.obj.x, end to end — the MRO is steps 1 and 3 of that procedureenumdataclass and attrs as class generators — that is an application of metaclasses and decorators, lesson 07super documentation — the write-up above is enough; the only useful thing in the documentation is the paragraph on the form with arguments.