Lesson · Iteration Protocol
collections.abc & Runtime Collection Interfaces
70 min readcollections.abc & Runtime Collection Interfaces
`collections.abc` describes runtime interfaces such as `Iterable`, `Sequence`, and `Mapping`. These abstract base classes let code reason about behavior rather than only concrete container types.
Learning goals
- Explain what a runtime check such as
isinstance([1, 2], Sequence)actually tests, and what it does not prove. - Name the capability each ABC adds:
IteratoroverIterable,SequenceandMappingoverCollection,MutableSequenceandMutableMappingover their read-only parents. - Pick the weakest annotation (
Iterable,Sized,Sequence,Mapping) that still supports a function's body. - Predict
isinstanceresults for lists, tuples, strings, sets, dicts, and mapping key views. - Explain why an ABC check and a static typing protocol can describe the same shape for different audiences.
Mental model
The tree is the point: every level adds capability, so an annotation should name the highest node the function actually needs. isinstance checks read this map at run time, and most built-in types sit on it through registration rather than inheritance. Callable is a separate branch because calling an object has nothing to do with iterating it.
Every level adds capability
annotate the highest node the body actually needs
Mental model
the same mechanism as a compact list
Iterable
├── Iterator adds __next__
└── Collection adds len() and in
├── Sequence adds integer indexing and slicing
│ └── MutableSequence adds assignment, insert, delete
├── Mapping adds key lookup
│ └── MutableMapping adds assignment and deletion
└── Set adds membership algebra
Callable stands apart: it is about being called with ()Core idea
An ABC in collections.abc is a named bundle of dunder methods, so a check against it asks about behavior rather than inheritance: isinstance([1, 2], Sequence) is true because list implements the sequence protocol, and any class that registers the same methods can pass too. That makes these names the vocabulary for function parameters: accept Iterable when you only loop, Sequence when you index, and Mapping when you look up by key, so the annotation documents exactly what callers must provide.
Iterable
The Iterable ABC marks objects whose type defines __iter__, and isinstance(obj, Iterable) tests for that method at run time. Its one job is to hand out an iterator to iter(), which every for loop, unpacking, and comprehension calls first.
Iterator
The Iterator ABC extends Iterable with __next__, marking objects that produce one value per call and raise StopIteration when the data ends. An iterator also implements __iter__ by returning itself, which is why it can be used anywhere an iterable is expected.
Collection
The Collection ABC combines Iterable, Sized, and Container, so it promises iteration, a definite len(), and support for in tests. Lists, tuples, strings, sets, dicts, and mapping views all register as collections.
Sequence
The Sequence ABC extends Collection with integer indexing and slicing through __getitem__, plus the mixins index, count, __contains__, and __reversed__. Lists, tuples, strings, and ranges are sequences; sets and dicts are not, because they have no positional order.
MutableSequence
The MutableSequence ABC extends Sequence with the write operations __setitem__, __delitem__, and insert, and mixes in append, extend, pop, remove, reverse, and __iadd__. list is the standard implementation, and the mixins derive the familiar list methods from the few abstract ones.
Mapping
The Mapping ABC marks read-only key-value containers that implement __getitem__, __iter__, and __len__, and it mixes in get, keys, items, values, __contains__, and __eq__. dict is the standard implementation, and any type that fits the same pair-lookup interface can register or inherit.
MutableMapping
The MutableMapping ABC extends Mapping with __setitem__ and __delitem__, and mixes in update, setdefault, pop, popitem, and clear. A function that only reads pairs should accept Mapping; one that writes them needs MutableMapping or a concrete dict.
Set
The Set ABC marks unordered collections of hashable elements that support in, len(), and iteration, and it mixes in the algebra operators &, |, -, ^, and isdisjoint. set and frozenset are the built-in implementations, and mapping key views such as d.keys() behave as sets too.
Callable
The Callable ABC marks objects whose type implements __call__, which is what the () application syntax needs. Functions, lambdas, classes, bound methods, and instances with a __call__ method all pass isinstance(obj, Callable).
Runtime interface checks
isinstance(obj, collections.abc.Sequence) and related checks ask whether an object is registered or recognized as supporting a runtime ABC. Static protocols and runtime ABC checks solve different problems.
ABCs vs static typing protocols
Abstract base classes live in collections.abc, support runtime isinstance checks and explicit register() calls, and can carry default mixin implementations. Static typing protocols describe the same method shapes for a type checker only and are erased at run time; use an ABC when the program must test an object, and a protocol when only the checker needs the contract.
Designing APIs around capabilities rather than concrete containers
Accept Iterable, Sequence, Mapping, or another behavioral interface when the algorithm only needs that capability. This gives callers more freedom than requiring a concrete list or dict.
Walkthrough
from collections.abc import Iterable, Sequence, Mappingimports three runtime interfaces; these names are classes used for checks and annotations, not classes you instantiate.def summarize(values: Iterable[int]) -> intdeclares the narrowest promise the body needs:sumonly iterates, so any iterable of numbers qualifies, including the set passed later.isinstance([1, 2], Sequence)printsTruebecauselistis registered as a sequence, meaning it supportslen, indexing, and slicing.isinstance({"a": 1}, Mapping)printsTruefor the dict, andsummarize({1, 2, 3})returns6because a set is iterable even though it is not a sequence. Predict before running: all three printed lines.
Experiments to try
- Add
print(isinstance({1, 2}, Sequence))andprint(isinstance("ab", Sequence)); explain why the set fails while the string passes. - Replace
Iterable[int]withSequence[int]in the signature and run the set call again: the output does not change, because annotations are not enforced at runtime; state which tool is supposed to flag the mismatch. - Check
isinstance(42, Callable)andisinstance(len, Callable); explain what theCallablecheck actually asks. - Print
isinstance({"a": 1}.keys(), Set)andisinstance([1, 2], Iterator); derive both results from the concept definitions.
Common mistakes
- Treating
isinstance(x, Iterable)as a guarantee of more than__iter__: it says nothing aboutlen, indexing, or whether the object can be iterated twice. - Annotating a parameter as
listwhen the body only loops: callers with tuples, sets, or generators are rejected by the type checker for no algorithmic reason, whileIterablestates the real requirement. - Assuming a passing
isinstancecheck proves the protocol: a class can be registered with an ABC without implementing every method, so the check is evidence about intent rather than proof of behavior. - Mixing up
IteratorandIterablein annotations: a function annotatedIteratorcannot accept a plain list, even though aforloop over that list works fine.
Practice: Easy
- Run the three worked example calls plus
print(isinstance({1, 2}, Sequence)); write all four expected results first, then check them. - Call
summarize((4, 5))and record the result; then callsummarize(["a", "b"])and read the error, stating which layer rejected the call. - Open
help(collections.abc.Sequence)and list its abstract methods versus its mixin methods; name one method the ABC provides without requiring an implementation.
Practice: Medium
- Write
first(items: Sequence)returningitems[0]; call it with a list and a tuple, then try a set and explain the mismatch between the annotation and the failing operation. - Change
summarizeto acceptCollection[int]so the body may also calllen(values); state which of a list, a set, and a generator expression still qualifies. - Take a function in your own code annotated
listand lower it to the weakest ABC that supports the body; list the new callers the annotation now accepts.
Practice: Hard
- Design
describe(obj)to testisinstanceagainstSequence,Mapping,Set, andCallablein a fixed order and report every interface that matches; define the expected output for[1, 2],{"a": 1},{1, 2}, andlen, and justify the order. - Write a class implementing only
__getitem__and__len__that inherits fromcollections.abc.Sequence; testin,reversed,index, andcounton it and list which methods came from the mixins. - Write the same "has
__len__" contract twice, once as a runtimeisinstance(obj, collections.abc.Sized)check and once as atyping.Protocolclass; state what each tool can verify and which audience each serves.
Lesson checklist
- I can name the capability each ABC adds on top of its parent.
- I can predict
isinstanceresults for lists, tuples, strings, sets, dicts, and key views. - I can pick the weakest annotation (
Iterable,Sized,Sequence,Mapping) that still supports the function body. - I can explain why a passing
isinstancecheck is evidence about a protocol, not proof of it.
Remember
`collections.abc` turns collection behavior into named, checkable interfaces: `Iterable` for loops, `Collection` for `len` and `in`, `Sequence` for indexing, `Mapping` for keys, `Set` for algebra, and `Callable` for calling. Functions should ask for the capability they use, which keeps callers free to pass lists, tuples, sets, views, or custom types that fit the same protocol. `isinstance` answers that question at run time, while the check itself only reports registration and method presence.
Interview angles
What is the main purpose of **Iterable**?+
The Iterable ABC marks objects whose type defines __iter__, so isinstance(obj, Iterable) tests for that method at run time. Its one job is to hand out an iterator to iter(), which every for loop, unpacking, and comprehension calls first.
What should you pay attention to when using **Iterator**?+
The Iterator ABC extends Iterable with __next__, marking objects that produce one value per call and raise StopIteration when the data ends. An iterator implements __iter__ by returning itself, which is why it can be used anywhere an iterable is expected.
How does **Collection** fit into this lesson?+
The Collection ABC combines Iterable, Sized, and Container, so it promises iteration, a definite len(), and support for in tests. Lists, tuples, strings, sets, dicts, and mapping views all register as collections.
Why is `Iterable` often a better parameter annotation than `list`?+
A parameter annotated Iterable states exactly what the function needs, so callers can pass a list, tuple, set, or generator. Annotating list forces callers to materialize a list even when the algorithm never indexes or mutates one.