Generics, Protocols & ParamSpec

P31.typing.02 · Audience: guest, it-ml, language-pro · Prerequisites: Gradual typing & mypy

Real LLM grading for this pageLLM grading (this page):

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).

Step 1 / 3Generics: one class, any type
ⓘ Concept: TypeVar makes a container type-safe
A 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.

Ctrl/Cmd + Enter to send

🎓 Practice ladder

3 graded rungs · ~30 min

Build 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.