Sub topic 11
Protocols you already use: Iterable, Sized and friends
You have been writing structural types for a long time. Every time you annotate a parameter as Iterable[str] or Sized, you are using a protocol. This chapter shows which standard-library types are protocols, how your own classes qualify for them, and where the exceptions are.
This chapter assumes you can write functions and classes, you know basic type hints, and you have read the earlier chapters on defining protocols and how a type checker decides a class matches. A checker such as mypy or pyright is assumed.
Annotations that are already structural
The collections.abc module defines many abstract classes. Type checkers (through the typeshed stubs) treat several of them as protocols. A class satisfies them by having the right special methods. It does not need to inherit from them.
from collections.abc import Iterable, Sized
def describe(items: Iterable[str]) -> str:
return ", ".join(items)
def is_empty(container: Sized) -> bool:
return len(container) == 0
print(describe(["a", "b"]))
print(describe(x for x in "cd"))
print(is_empty({}))A list, a generator and a dict all work here, though none of them inherits from Iterable or Sized in your code. The annotation says "I need something I can loop over" or "I need something with a length", and nothing more.
The protocols in the standard library
The table lists the most useful ones. Each is a protocol in typeshed, so a type checker accepts any class with the listed methods.
| Type | Required methods | What it promises |
|---|---|---|
| `Iterable[T]` | `__iter__` | You can loop over it with `for`. |
| `Iterator[T]` | `__iter__`, `__next__` | It produces values one at a time. |
| `Sized` | `__len__` | `len(x)` works. |
| `Container[T]` | `__contains__` | `x in obj` works. |
| `Collection[T]` | `__len__`, `__iter__`, `__contains__` | All three of the above. |
| `Reversible[T]` | `__reversed__` (and `__iter__`) | `reversed(x)` works. |
| `Hashable` | `__hash__` | It can be a dict key or set member. |
| `Awaitable[T]` | `__await__` | You can `await` it. |
The typing module adds single-method protocols for conversions: SupportsInt, SupportsFloat, SupportsIndex, SupportsAbs, SupportsRound and SupportsBytes. Each requires one dunder method such as __int__ or __float__.
Making your own class qualify
Implement the methods and the class qualifies. There is no registration step and no base class.
from collections.abc import Iterable, Iterator, Sized
class Countdown:
def __init__(self, start: int) -> None:
self.start = start
def __iter__(self) -> Iterator[int]:
return iter(range(self.start, 0, -1))
def __len__(self) -> int:
return self.start
def total(numbers: Iterable[int]) -> int:
return sum(numbers)
def count(items: Sized) -> int:
return len(items)
print(total(Countdown(3))) # 6
print(count(Countdown(3))) # 3Countdown satisfies both Iterable[int] and Sized. The checker compares the method signatures. If you declared __len__ as returning str, the call to count would be an error.
Iterable versus Iterator
These two are easy to confuse, and the difference causes real bugs.
- An
Iterablecan produce a fresh iterator each time you calliter()on it. Lists, tuples, dicts and sets are iterables you can loop over repeatedly. - An
Iteratoris a single pass over the data. Its__iter__returns itself, and once it is exhausted it stays empty. Generators and file objects are iterators.
Every iterator is also an iterable, so the annotation Iterable[int] accepts both. A function that loops twice over an Iterable parameter will therefore pass type checking and still misbehave on an iterator.
from collections.abc import Iterable
def report_buggy(values: Iterable[int]) -> None:
print(sum(values), max(values))
def report_fixed(values: Iterable[int]) -> None:
data = list(values) # materialize once
print(sum(data), max(data))
report_buggy([3, 1, 2])
report_fixed(iter([3, 1, 2]))
try:
report_buggy(iter([3, 1, 2]))
except ValueError as exc:
print("buggy version failed:", exc)sum consumes the iterator, so max sees an empty sequence and raises ValueError. If your function needs more than one pass, copy the values into a list first. Alternatively, ask for Collection or Sequence so that callers cannot pass a one-shot iterator.
Combining protocols: Collection and your own mixes
A generator has __iter__ but no __len__, so it is not Sized. If a function needs both looping and a length, Collection expresses that. The same function accepts lists, tuples, sets and dicts, and a checker rejects generators.
from collections.abc import Collection
def summarize(items: Collection[str]) -> str:
if len(items) == 0:
return "nothing"
marker = "has a" if "a" in items else "has no a"
return f"{len(items)} items ({marker}): {', '.join(items)}"
print(summarize(["a", "b"]))
print(summarize(("x", "y", "z")))
print(summarize({"k": 1}))
print(summarize(set()))When no standard protocol matches the exact combination you need, define one by inheriting from existing protocols. You must list Protocol explicitly among the bases, or the result is an ordinary class.
from collections.abc import Iterable, Sized
from typing import Protocol
class SizedIterable(Sized, Iterable[str], Protocol):
pass
def shout(items: SizedIterable) -> str:
return f"{len(items)}: " + " ".join(s.upper() for s in items)
print(shout(["hi", "there"]))In practice Collection[str] is simpler. Define a custom combination only when you need to leave out a member such as __contains__.
Conversion protocols: the Supports family
The Supports* protocols describe "can be converted to X". They are more permissive than naming concrete classes such as int or float.
from collections.abc import Iterable
from fractions import Fraction
from typing import SupportsFloat
def average(values: Iterable[SupportsFloat]) -> float:
items = [float(v) for v in values]
return sum(items) / len(items)
print(average([1, 1.5, Fraction(1, 2)])) # 1.0int, float and Fraction all define __float__, so all are accepted. A str is not, and a checker reports it, even though float("3") works. The protocol describes the dunder method, not the behaviour of the float constructor.
Where the standard library is not structural
Not every collections.abc type is a protocol, and this is the most common source of surprise.
Sequence,Mapping,MutableMapping,Setand similar are ordinary nominal ABCs in the stubs. A class with__getitem__and__len__is not aSequenceto a type checker. It must inherit fromSequenceor be a built-in that does.- A class that only defines
__getitem__can be looped over at runtime through Python's legacy iteration protocol. It is still notIterablefor the checker, andisinstance(obj, Iterable)returnsFalse, because that check looks for__iter__only. stris anIterable[str]. Passing"abc"todescribefrom the first example compiles and joins the characters asa, b, c. If a bare string would be a bug, add a runtime guard or acceptSequence[str]and check forstrexplicitly.Callableis special-cased by the type system. It behaves structurally, but you cannot subclass it as a protocol. Use a callback protocol with__call__when you need keyword-only parameters or defaults.
The runtime behaviour has one more detail. The collections.abc classes implement isinstance checks themselves through __subclasshook__, so isinstance([], Iterable) works without @runtime_checkable. Like decorated protocols, they check only that the method exists and not its signature.
Choosing between standard protocols and your own
- If a standard protocol names exactly what you use, use it. Readers recognize it and checkers already understand it.
- If you need a combination, try
Collection,SequenceorMappingbefore writing a new protocol. - If you need one method that the standard library does not name, write a small protocol. The earlier chapters cover how.
Exercise
A function takes values: Iterable[float] and computes sum(values) / len(list(values)). It works for a list but returns a wrong answer for a generator, with no type error. Why, and what is the smallest change that fixes it?
Show answer
A generator is a one-shot iterator. sum(values) consumes it, so list(values) afterwards is empty and the division is by zero or by the wrong count. The checker cannot catch this because Iterable accepts iterators. The fix is to build the list once, for example data = list(values) and then sum(data) / len(data). Alternatively, change the parameter to Collection[float] so that generators are rejected.
Exercise
You write a class Playlist with __getitem__(self, i: int) -> str and __len__(self) -> int, and no base class. Is it accepted where Sequence[str] is required? Is it accepted where Sized is required? Where Iterable[str]?
Show answer
It is rejected for Sequence[str], because Sequence is a nominal ABC in the stubs and the class does not inherit from it. It is accepted for Sized, because it has __len__. It is rejected for Iterable[str], because it has no __iter__, even though a for loop would work at runtime through the legacy __getitem__ protocol. Adding an __iter__ method fixes the Iterable case.