An interface in Python is not a declaration but a set of dunders that the interpreter looks up directly in the type. Hence duck typing, len() as a function, and why checkable contracts were bolted onto the language twice — in 2007 and in 2017.
Commit to an output and a reason before you open the answer.
class G:
def __getattr__(self, n):
return lambda *a: 0
print(len(G()))TypeError: object of type 'G' has no len()The interceptor synthesizes any attribute, including __len__. And it still does not work.class Sized:
def __init__(self, n): self.n = n
def __len__(self): return self.n
if Sized(0):
print("true")
else:
print("false")falseThe object exists, the field is filled in, and yet in a condition it is false.from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
class Raw:
def close(self): pass
print(isinstance(Raw(), Closeable))TrueRaw inherits nothing and knows nothing about Closeable.from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def go(self): ...
Base()TypeError: Can't instantiate abstract class Base
with abstract method goAn error when an instance is created, not when the class is declared.Lesson 04 took apart the attribute lookup procedure. Here: an important exception to it, on which the language's whole system of interfaces rests.
Special methods are looked up in the type, bypassing the instance. When the interpreter itself calls __len__, __iter__, __add__, it does not go through the four-step procedure — it reads the corresponding slot in the type object.
A slot is a field in the type structure, filled at class creation from the dunder of the same name. So accessing it costs one read, not a search through the MRO.
A protocol is a set of slots that must be filled. No declaration, no registration: a type either has the required slots or it does not.
len(x) and not x.len()The len function reads the slot directly. If it were a method, it would have to be looked up by the ordinary procedure — with a walk of the MRO, descriptors and the creation of a bound method on every call. The slot removes all of that at once.
Hence the overall look of the language: len, iter, next, str, operators, with, in — all of them look like functions and syntax rather than methods, because all of them read slots. This is not style but a direct consequence of where the protocol lives.
Snippet A becomes obvious. __getattr__ is step four of the procedure from lesson 04, and an implicit call never even reaches that procedure: the interpreter looks into the type's slot and finds it empty.
This matters more than it seems, because it affects a whole class of techniques. A proxy object, a lazy loader, a stub object — anything that synthesizes attributes on the fly will not become iterable, callable or comparable that way 🔒. Dunders have to be declared explicitly on the class, and that is exactly why proxy libraries list them out in code.
Snippet B. Truth testing goes by protocol: first __bool__ is asked, if there is none then __len__, and only if both are absent is the object considered true. By implementing a length you automatically changed the behaviour in if.
The logic is right — an empty container should be false — but the consequence is not obvious: any object with a __len__ that returned zero is false. Hence the classic mistake of if not response on an object whose length means the number of elements, not the presence of the object itself.
Since a protocol is the presence of slots, the question “does the class implement the interface” originally had no answer: the only way to find out was to try the call. Over a quarter of a century two answers appeared.
ABC (2007) is nominal: a class declares inheritance or is explicitly registered, and @abstractmethod forbids creating an instance until the method is overridden. Snippet D shows the moment of the check: not at class declaration but at the attempt to create an object — the abstract methods left unimplemented are counted.
Protocol (2017) is structural: a match by shape, without inheritance and without the class author's knowledge. Snippet C: Raw fits simply because it has close. The main mode is static checking by a type checker; runtime_checkable adds isinstance, but it checks only the presence of methods, not their signatures.
The choice follows from this difference: ABC — when you need a shared implementation and explicit kinship; Protocol — when you are describing an expectation of someone else's code that you cannot touch.
runtime_checkable checks only names. isinstance with a Protocol looks at whether the methods exist, not at their signatures and types. A class with a method close(self, force, timeout) will pass the check and fail on the call. The real check is static.
Slots are filled when the class is created. Assigning obj.__len__ = ... to an instance is useless: the slot is taken from the type. Adding a dunder to a class after creation does work 🔧, because CPython updates the slots when a class changes — but that is an implementation detail.
Protocols partly overlap. Iterability comes not only from __iter__ but also from the old protocol through __getitem__ with integer indices. So an object without __iter__ is sometimes iterable anyway — and that is not a bug but a legacy kept for compatibility.
Root R4: an interface is defined by behaviour, not by declaration. The decision was made at the very beginning and for an entirely practical reason: types written in C and types written in Python had to work the same way. A slot in the type structure is something a C extension fills in naturally, with a function pointer.
That is, Python's system of interfaces grew not out of the idea of duck typing but out of the requirement of compatibility with C — the same root R6 that would later give the scientific stack and keep the GIL from being removed. Duck typing turned out to be a consequence, not a goal.
The price became clear later: without declarations you can neither check a contract nor express it in a function signature. Twice this was fixed with an extension — first nominal (ABC), then structural (Protocol) — and both times without touching the original mechanism.
A slot in the type structure is a vtable, and the comparison is exact. A virtual call in C++ goes through a table of function pointers attached to the type; a call to len(x) in Python goes through the field tp_as_sequence->sq_length in the type structure. Both constructs exist precisely so as not to look a method up by name at call time.
The difference is who fills the table. In C++ the compiler does it from the class declaration; in Python the interpreter does it when the type is created, copying the same-named dunders in. Hence consequence 2: the slot is filled from the type, and once, rather than asked of the object on every call — which is why an attribute interceptor cannot reach it.
And checking “does the type meet the requirement” is C++20 concepts, and here Python with its Protocol arrived at the same answer independently: describe the shape, not the pedigree.
Questions that come up on their own if you read closely. The answer is under the question.
len(x) and not x.len()?Because len has to be fast and the same for everyone, and a method has to be neither.
The len function goes straight to the type's tp_as_sequence->sq_length slot — a read of a structure field and a call to a C function, bypassing the whole attribute lookup procedure from lesson 04. A method x.len() would go the full way: data descriptors, the instance's __dict__, the MRO.
The second argument is a uniform interface. len, iter, str, abs, hash — all built-in functions with the same syntax for all types. There is no object whose “length” is called size, count or length: implement __len__ and len() works. Guido put it as “prefix notation for operations that apply to many types”.
class G:
def __len__(self): return 3
g = G()
print(len(g)) # → 3
g.__len__ = lambda: 99 # substitute it on the instance
print(len(g), g.__len__()) # → 3 99 len takes it from the type
The last line is the main consequence: a dunder is read from the type, not from the object. That is why __getattr__ cannot synthesize a protocol, and proxy libraries are forced to list the dunders out in the class's code.
The price of the decision: the set of protocols is fixed. You cannot write your own “built-in function” with the same speed — it will be an ordinary call.
ABC — when the contract is yours and you want to impose it. Protocol — when the contract describes other people's classes.
The difference is the direction of dependency. ABC requires explicit inheritance or registration: the class must know about your interface. Protocol is checked structurally: anything with the required methods fits, and the class knows nothing about the protocol.
from typing import Protocol, runtime_checkable
from abc import ABC, abstractmethod
class Reader(Protocol): # structurally
def read(self, n: int) -> bytes: ...
class Base(ABC): # nominally
@abstractmethod
def read(self, n: int) -> bytes: ...
class Mine:
def read(self, n): return b""
print(isinstance(Mine(), Base)) # → False did not inherit
# Mine fits Reader without a single line about Reader
The practical rule. If you are writing a library and accepting someone else's object — Protocol: the user will not have to inherit from your class and pull in a dependency. If you are building a hierarchy inside your own code, where it matters that a descendant does not forget a method — ABC: it will not let an instance be created with an unimplemented @abstractmethod.
Both, incidentally, were bolted onto the language much later: ABC in 2007 (PEP 3119), Protocol in 2017 (PEP 544). The fifteen years between them are exactly the time it took to become clear that a nominal check does not fit duck typing.
And runtime_checkable checks only the presence of methods, not signatures — that is, isinstance with a protocol is much weaker than it seems.
Because “quacks like a duck” cannot be checked without quacking.
Before ABCs the only way to find out whether an object supported an interface was hasattr — and that worked badly for two reasons. First, the presence of a method does not mean the right semantics: a string has __getitem__ and __len__, but treating it as a list is usually a mistake. Second, interfaces are composite — a “sequence” is five methods, and checking them one by one in every function is inconvenient.
from collections.abc import Sequence, Iterable, Hashable
print(isinstance("abc", Sequence)) # → True
print(isinstance({1: 2}, Iterable)) # → True
print(isinstance([1], Hashable)) # → False
collections.abc gave these names and one check instead of five. Plus the mechanism of virtual registration: someone else's class can be declared an implementation of an interface without touching its code and without inheriting.
from collections.abc import Sized
class Weird:
def __len__(self): return 0
Sized.register(Weird)
print(isinstance(Weird(), Sized)) # → True
And the second use, the one ABCs are used for more often: mixin methods. Inherit from Mapping, implement three methods — and get keys, values, items, get, __contains__ and __eq__ for free and consistent with the rest of the language.
So ABCs do not cancel duck typing; they give it a vocabulary and ready-made parts. The real replacement appeared only with Protocol.
Because special methods are looked up in the type, bypassing the object's __dict__ and __getattr__.
This is not a “just in case” optimization but a necessity: a + b, len(x), x[i] are executed millions of times, and a full attribute lookup on every operation would cost twice as much as the operation itself. So the interpreter reads a ready pointer from the type's slot.
class C: pass
c = C()
c.__add__ = lambda other: "from the instance"
try:
c + 1
except TypeError as e:
print(e) # → unsupported operand type(s) for +: 'C' and 'int'
print(c.__add__(1)) # → from the instance an explicit call works
Two practical consequences.
First: proxies and wrappers cannot be written through __getattr__. A class that transparently forwards everything to an inner object has to declare every dunder explicitly — __len__, __iter__, __getitem__ and so on. That is exactly why unittest.mock.MagicMock contains a long list of dunders right in its code, and the ordinary Mock does not support them.
Second: dunders must be assigned to the class, not to the object — and that does work, because CPython recomputes the slots when a class changes 🔧:
C.__add__ = lambda self, other: "from the class"
print(c + 1) # → from the classlen() as a function rather than a method: a slot is read in one access, whereas a method would require a walk of the MRO and the creation of a bound method. Hence also the fact that __getattr__ cannot synthesize a dunder — an implicit call never reaches that step, and proxy objects are forced to list special methods explicitly. A protocol has wider effects than it seems: by implementing __len__ you changed the object's behaviour in if, because truthiness is checked through __bool__ and, when it is absent, through the length. The language originally had no checkable contracts, and they were bolted on twice: ABC in 2007 as a nominal mechanism checked at instance creation, Protocol in 2017 as a structural one that works without inheritance and without the class author's knowledge.C++20 concepts are the closest point. A concept describes requirements on a type by shape: which operations on it are allowed. The check is structural and entirely at compile time; the type inherits from nothing and knows nothing about the concept. This is literally Protocol, only twenty years earlier in conception and with no runtime variant. Before concepts the same role fell to SFINAE, and the diagnostics were unreadable — a direct analogue of Python before 2017, where a protocol mismatch showed up as an AttributeError somewhere deep inside.
Go made structural typing the main mechanism: a type implements an interface if it has the required methods, and there is no need to declare it. What Python arrived at through Protocol, Go had from day one — but there it is always checked, and mandatorily.
Java is the opposite pole: nominal only, implements is required. Hence adapters and wrappers where Go and Python get by with a match in shape.
Three points on one axis: nominal always, structural always, structural in fact with an optional check.
if not response on an object with a length__len__ was implemented — and the object became false at zero length; the branch went the wrong wayA convenient len() was added to the response class. A week later a successful empty response was caught being handled as an error.
class Response:
def __init__(self, items, status):
self.items, self.status = items, status
def __len__(self):
return len(self.items) # added for convenience
resp = api.fetch()
if not resp: # written before that
raise ApiError("empty response")
Before, Response had neither __bool__ nor __len__, and if not resp meant “there is no object”. After the length was added it came to mean “there are no elements” — a successful response with an empty list went into the error branch.
Review lets it through twice: first, adding __len__ looks like a harmless improvement, and then the check if not resp in another file is in no way connected to it in the diff. This is consequence 3 in its pure form — implementing one protocol changes behaviour in a construct nobody was thinking about.
Two ways to fix it, and the choice is meaningful. Either declare truthiness explicitly and detach it from the length:
def __bool__(self):
return True # the object is always true; the length is about the elements
Or make the check unambiguous where it stands: if resp is None or if not resp.items. The general rule follows from the mechanism: if you implement __len__ on something that is not a container, implement __bool__ too — otherwise the protocol will decide for you.
get_items() method — and the object works in everything that knows how to iterateA class that accumulates data usually acquires a “give me the list” method. The protocol makes it unnecessary and removes the copying along the way.
class Batch:
def __init__(self): self._rows = []
def get_rows(self): # what people write out of habit
return list(self._rows) # and a copy on every call, too
class Batch:
def __init__(self): self._rows = []
def __iter__(self): return iter(self._rows)
def __len__(self): return len(self._rows)
def __contains__(self, x): return x in self._rows
After that the object works in everything that reads protocols, without a single extra line:
for row in batch: ...
len(batch)
x in batch
sorted(batch)
list(batch)
sum(r.n for r in batch)
first, *rest = batch
The gain is not only convenience. get_rows() creates a copy of the list on every call — memory and time in proportion to the number of elements, exactly the arithmetic of lesson 03. __iter__ hands out an iterator that copies nothing.
When not to do this: if the object is not a collection but an entity with a collection inside. Then __iter__ on it is misleading, and it is more honest to expose the list itself as a property. The test is simple: if the phrase “iterate over this object” sounds natural, the protocol fits; if it needs the qualification “iterate over its elements”, it does not.
Run the four snippets and check them against your prediction. Then:
class Old:
def __getitem__(self, i):
if i > 2: raise IndexError
return i
list(Old())
# There is no __iter__. Why does it work anyway?
class C: pass
c = C()
c.__len__ = lambda: 5
len(c)
# And if you assign C.__len__ instead of c.__len__?
from collections.abc import Iterable, Sized
isinstance([], Iterable), isinstance([], Sized)
issubclass(list, Iterable)
# list inherits none of this. How does the check pass?
import numbers
isinstance(3, numbers.Number), isinstance(3.0, numbers.Number)
# Why does the standard library have a numeric hierarchy, if there are int and float?
The third question leads to __subclasshook__ — the mechanism by which an ABC can recognize as its own classes that know nothing about it. A bridge from nominal to structural, built ten years before Protocol.
Lib/_collections_abc.py. This is where Iterable, Sized, Mapping and the rest live — and where you can see how an ABC can be structural. Find __subclasshook__ on Iterable: it checks for __iter__ in the candidate's MRO and on that basis recognizes it as a subclass. That is why issubclass(list, Iterable) is true, although list inherits from nothing of the kind.
Notice one more thing: some of these classes provide a ready implementation on top of a minimum. Implement __getitem__ and __len__, inherit from Sequence, and you get __contains__, __iter__, __reversed__, index and count for free. That is the answer to “why ABC if there is Protocol”: Protocol only describes, ABC also finishes the job.
Lib/typing.py, the Protocol class. Look at how runtime_checkable is built and why its check has not a word about signatures — the limitation from the “Limits of the model” section is visible right in the code.
From L1 you know that a protocol is a set of filled slots. Here: exactly how they get filled.
A type structure in CPython contains fields such as tp_iter, tp_call, tp_richcompare, as well as the sub-structures tp_as_number, tp_as_sequence, tp_as_mapping with fields for arithmetic, indexing and length. When a class is created, the interpreter walks a table of “dunder name — slot” correspondences and fills the slots with adapters that call the Python function.
The reverse operation exists too: on a type written in C, dunders appear as attributes synthesized from the filled slots. That is why list.__len__ exists, although there is no def __len__ anywhere in the sources of list.
print(list.__len__)
# → <slot wrapper '__len__' of 'list' objects>
print(type(list.__len__))
# → <class 'wrapper_descriptor'>
The very words slot wrapper in the output point straight at the mechanism.
What this saves: an ordinary access obj.method goes through four steps and creates a bound method, and so allocates an object. Reading a slot is dereferencing a structure field. For operations executed in every loop — comparison, addition, taking a length, an iterator step — the difference is fundamental, and that is exactly why protocols are made of slots rather than of a naming convention for methods.
Tag v3.11.15.
Objects/typeobject.c, the slotdefs table — the correspondence “dunder name ↔ type-structure field”, a few hundred lines. The most direct answer to what counts as a protocol at all.fixup_slot_dispatchers and update_one_slot — filling the slots when a class is created, and updating them when a class is changed after the fact.Include/cpython/object.h — the PyTypeObject structure itself. Worth looking at once: half the lesson becomes obvious from a single glance at the list of fields.Protocol; the motivation compares it directly with Go's interfaces.obj.x, end to end — the lookup procedure from which dunders are made an exceptionwith protocol and what __exit__ can doruntime_checkable with its limitations.collections.abc documentation — the write-up above is enough; the table “which methods you provide — which you get” is useful.