Generics, Protocols & ParamSpec
P31.typing.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Gradual typing & mypy
Where next?
Later in Typing
Go up a level
P31.typing.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Gradual typing & mypy
Later in Typing
Go up a level
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).
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 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.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
Build a generic Stack behind a Protocol, type a
decorator with ParamSpec, then explain gradual typing in an
interview.
Loading exercise…
Loading exercise…
Loading exercise…
You can now type the tricky parts. The capstone puts it together: take an untyped module to a green type contract.
Loading your notes...