Sub topic 11
Protocols you already use: Iterable, Sized and friends
This chapter assumes you can write functions and classes with type hints. It also assumes you know what typing.Protocol is from the earlier chapters and that you have used a checker such as mypy or pyright. Here you will see that many common annotations are protocols, so you were already using structural subtyping.
Annotations that describe shape
A parameter annotated list[str] demands a list. A parameter annotated Iterable[str] demands only that the object can be looped over. Iterable is defined in collections.abc and is declared as a protocol in typeshed, the type stubs that mypy and pyright use. Any class with a compatible __iter__ method qualifies, with no inheritance.
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. None of them inherits from Iterable or Sized. They simply have the right special methods.
Your own classes qualify too
from collections.abc import Iterable, Iterator, Sized
class Playlist:
def __init__(self, titles: list[str]) -> None:
self._titles = titles
def __iter__(self) -> Iterator[str]:
return iter(self._titles)
def __len__(self) -> int:
return len(self._titles)
def describe(items: Iterable[str]) -> str:
return ", ".join(items)
def is_empty(container: Sized) -> bool:
return len(container) == 0
songs = Playlist(["Intro", "Outro"])
print(describe(songs))
print(is_empty(songs))Playlist satisfies Iterable[str] because of __iter__, and Sized because of __len__. The checker compares members, as described in the chapter on how a checker decides a class matches.
The common protocols
| Annotation | Required method | Typical use |
|---|---|---|
| `Iterable[T]` | `__iter__` | Anything you loop over once |
| `Iterator[T]` | `__iter__`, `__next__` | Objects you step through with `next()` |
| `Sized` | `__len__` | You only need `len()` |
| `Container[T]` | `__contains__` | You only need `in` |
| `Collection[T]` | all three above | Sized, iterable and supports `in` |
| `Hashable` | `__hash__` | Dictionary keys, set members |
| `SupportsInt`, `SupportsFloat`, `SupportsAbs` (from `typing`) | `__int__`, `__float__`, `__abs__` | Values you convert or measure |
Sequence, Mapping and Set are different. They are abstract base classes, and checkers treat them nominally. A class must inherit from them or be registered to count as one.
Pick the narrowest annotation
Ask what the function does with the argument. If it loops once, use Iterable. If it needs len() and a second pass, use Collection. Reserve list for code that must index or mutate.
from collections.abc import Collection
def summary(items: Collection[str]) -> str:
return f"{len(items)} items: {', '.join(items)}"
print(summary(["x", "y"]))
print(summary({"only"}))A generator would be rejected here because it has no __len__. That is the correct result, since len() would fail on it at runtime.
Runtime behavior and limits
The ABCs in collections.abc also work with isinstance. isinstance([], Iterable) is True. The check looks only for the method name on the class. An old-style class that supports looping through __getitem__ alone works with for, but it fails isinstance(obj, Iterable) and a type checker rejects it as an Iterable. Also, str is Iterable[str], so describe("abc") passes the checker and joins single characters. A string passed by mistake instead of a list of strings will not be caught.
Exercise
Exercise
A function total_length(words: ...) loops over words once, adding up len(word) for each word. It never calls len(words). Which annotation is the best fit, and why would Collection[str] be needlessly strict?
Show answer
Iterable[str]. The function needs only __iter__. Collection[str] would also require __len__ and __contains__, so it would reject generators that the function could handle fine.
Exercise
Why does summary(x for x in "ab") fail type checking when summary takes Collection[str], even though the generator is iterable?
Show answer
A generator has __iter__ but no __len__ or __contains__, so it does not match the Collection protocol, which requires all three.