Generics, Protocols & ParamSpec
P31.typing.02 · Audience: guest, it-ml, language-pro · Prerequisites: Gradual typing & mypy
Basic annotations type the easy cases. This module types the hard ones: a container that works for any element type (generics), a "anything shaped like this" type (Protocols), and the piece that finally lets you type the decorators from P29 (ParamSpec).
ⓘ Concept: TypeVar makes a container type-safe
TypeVar("T") plus Generic[T] lets a Stack[int] and a Stack[str] share one class while the checker still knows pop() returns a T. The built-in collections are generic the same way — list[int], dict[str, float].Why it matters — Without generics a container is either Any (no checking) or duplicated per type; TypeVar gives you one implementation the checker still understands.
Ask the mentor about this module
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
🎓 Practice ladder
3 graded rungs · ~30 minBuild a generic Stack behind a Protocol, type a
decorator with ParamSpec, then explain gradual typing in an
interview.
Rung 1 — a generic Stack and a runtime Protocol
Loading exercise…
Rung 2 — type a decorator with ParamSpec
Loading exercise…
Rung 3 — gradual typing, mypy and Protocol vs ABC (interview)
Loading exercise…
You can now type the tricky parts. The capstone puts it together: take an untyped module to a green type contract.
Where next?
Later in Typing
Go up a level