Lesson · Type Hints & Static Typing
Collection & Callable Types
71 min readCollection & Callable Types
Typing collections and callables is about the interface a function consumes, not only the concrete class a caller happens to use. Abstract types such as `Iterable`, `Sequence`, and `Mapping` often create better APIs.
Learning goals
- Annotate function parameters with the abstract types
Iterable,Sequence, andMapping, and say what each one promises callers. - Write a
Callable[[int], int]annotation and explain the two nested bracket pairs. - Explain the iterable versus iterator split and why a generator fits
Iterator[int]but notSequence[int]. - Choose between
list[str],tuple[int, ...], andset[str]for an input and predict the operations each choice advertises. - Read
Mapping[str, int]as a read-only lookup promise and say why a plaindictstill satisfies it.
Mental model
Pick the weakest annotation that still supports what the body does: if the function only loops, Iterable accepts every concrete collection, and asking for Sequence or Mapping adds promises the body may not need.
Mental model
read it top to bottom
caller's value annotation what the annotation promises list, tuple, set, str, gen → Iterable[int] anything a for loop can walk list, tuple, str → Sequence[str] iteration plus ordered access and len() dict → Mapping[str, int] read-only key lookup function or lambda → Callable[[int], int] callable with one int returning one int
Core idea
A parameter's annotation states the smallest interface the function will actually use, and any concrete value that supports that interface is accepted. Abstract types from collections.abc express those interfaces: Iterable promises a loop, Sequence adds ordered access, Mapping adds key lookup, and Callable promises the value can stand in for a function. Choosing the most general type that still supports the body's operations is what keeps an API open to every caller who has the right shape.
list[str]
list[str] is a list subscripted with its item type: it says the value is a list whose items are strings. At runtime the subscription builds a types.GenericAlias, so it belongs in annotations and raises TypeError inside isinstance.
dict[str, int]
dict[str, int] names a mapping from string keys to integer values, spelled as the dict class subscripted with key and value types. It advertises full mutability, since insert, delete, and update all stay available; Mapping[str, int] is the read-only spelling of the same shape.
tuple
tuple[int, ...] is a homogeneous tuple of any length, while tuple[int, str] is a fixed pair with one integer and one string, position by position. Use the fixed form for record-like shapes and the ellipsis form when only the item type matters.
set
set[str] describes an unordered collection of unique items with fast membership checks. Because sets have no order and no indexing, a function that needs positional access should ask for a sequence instead.
Callable
Callable[[int], int] describes a callable that takes one integer and returns an integer: the first list holds the parameter types and the second slot holds the return type. A bare Callable accepts anything callable, at the price of saying nothing about the signature.
Iterable
Iterable[int] promises only that iter() works, meaning a for loop or sum() can walk it. That is the weakest promise, so it accepts lists, sets, generators, and anything else with __iter__.
Iterator
An Iterator[int] is the object iter() hands back: it keeps its own position and is consumed once as it yields. It also satisfies Iterable, but not Sequence, since you cannot index it or ask for its length.
Sequence
Sequence[str] promises ordered access: indexing, len(), slicing, and iteration. Lists, tuples, and strings all satisfy it, which makes it right for functions that need position without demanding a mutable list.
Mapping
Mapping[str, int] promises read-only key lookup with [], get(), in, and iteration over keys. A dict satisfies it, so a function that only reads can accept Mapping and leave the choice of concrete mapping to the caller.
Walkthrough
total(values: Iterable[int])accepts anything aforloop can walk, which is why the call site can pass the set{1, 2, 3}instead of a list;sum()does the looping internally.first(values: Sequence[str])needsvalues[0], so it asks for the stronger promise that includes indexing; a generator would be rejected by a checker here even thoughtotalwould accept one.apply(fn: Callable[[int], int], value: int)calls whatever it receives with one integer, so the lambdax: x * 2fits; nothing checks the annotation when the call runs.- Predict before running: the three printed results, what
firstwould raise if you passed(x for x in "ab"), and which annotation would have to change for that generator to be legal.
Experiments to try
- Pass a tuple, a set, and a
rangetototalin turn and explain why all three satisfy a checker that asks only forIterable[int]. - Replace
Iterable[int]intotalwithSequence[int]; state which of those three values now fail the annotation and why the body did not get any stronger. - Feed
firsta generator expression, read the runtimeTypeError, then wrap the generator inlist()and confirm it works. - Write
apply(lambda x: x > 0, 5)and explain why the annotation claims anintresult while Python happily runs the call and prints a boolean.
Common mistakes
- Annotating inputs as
list[int]out of habit: that demands the concrete list class, so a checker rejects a caller holding a tuple, a set, or a generator even though the body could iterate any of them. - Asking for
Sequencewhen the body only iterates: the stronger promise rejects one-pass inputs such as generators for no benefit the code actually uses. - Reusing a parameter annotated
Iterator[int]: the object is consumed as it yields, so a second loop over the same argument produces nothing, and no annotation can restart it. - Calling mutation methods through a
Mappingannotation: the promise is read-only by design, sohandlers.update(...)is flagged even when the runtime object happens to be adict.
Practice: Easy
- Run the worked example, then call
totalwith a tuple and with arange; confirm the same result and explain whytotaldoes not care which collection it receives. - Write
last(values: Sequence[str]) -> str:and call it with a list, a tuple, and the string"ab"; explain why all three are legal. - Annotate a parameter
counts: dict[str, int]and mutate it inside the function withcounts["new"] = 0; then change the annotation toMapping[str, int]and explain why a checker now complains about the same line.
Practice: Medium
- Rewrite a
def join_words(words: list[str]) -> str:signature to takeIterable[str]; name two call sites that become legal only after the change and confirm each works at runtime. - Compare
tuple[int, ...]andtuple[int, str]: annotate a function with each and give one argument that fits only the first and one that fits only the second. - Write
dispatch(handlers: Mapping[str, Callable[[int], int]], name: str, value: int) -> int:that looks up a handler and applies it; then call it with a missing name usinghandlers[name]and withhandlers.get(name)and describe the two outcomes.
Practice: Hard
- Build
summarize(values: Iterable[float]) -> dict[str, float]returning count, total, and mean; test it with a list, a tuple, and a generator, and note which input type a second call with the same generator breaks. - Failure lab: trigger the
TypeErrorfromfirst(generator), the empty second pass over a consumed iterator, and a checker complaint abouthandlers.update(...)behind aMappingannotation that still runs at runtime; explain each mechanism. - Explain why
Sequencedescribes behavior rather than inheritance, and name two built-in types that satisfy it without inheriting from any typing class.
Lesson checklist
- I can choose
Iterable,Sequence, orMappingfrom the operations the function body actually performs. - I can write a
Callable[[int], int]annotation and read its two bracket pairs. - I can explain why a generator satisfies
Iteratorbut notSequence. - I can predict which concrete values a checker accepts for a given annotation.
Remember
Collection annotations describe the interface a function needs, and `collections.abc` supplies the vocabulary: `Iterable` for anything a loop can walk, `Sequence` when position matters, `Mapping` for read-only lookup, and `Callable` for values that stand in for functions. The worked example makes the choice visible, since `total` accepts a set while `first` demands indexing. Ask for the weakest type that still supports the body's operations, and both the checker and your callers stay happy.
Interview angles
What is the main purpose of **list[str]**?+
list[str] is a list subscripted with its item type: it says the value is a list whose items are strings. At runtime the subscription builds a types.GenericAlias, so it works in annotations and fails in isinstance.
What should you pay attention to when using **dict[str, int]**?+
dict[str, int] names a mapping from string keys to integer values and advertises full mutability, since insert, delete, and update stay available. Mapping[str, int] is the read-only spelling of the same shape.
How does **tuple** fit into this lesson?+
tuple[int, ...] is a homogeneous tuple of any length, while tuple[int, str] is a fixed pair with one integer and one string, position by position. Use the fixed form for record-like shapes and the ellipsis form when only the item type matters.
Why can a function that takes an `Iterator[int]` quietly produce nothing when the same argument is passed twice?+
An iterator keeps its own position and is consumed as it yields, so after the first pass it is exhausted and the second loop runs zero times. The annotation describes the object; it does not copy or restart it.