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 / 3 — Generics: 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.

Images, PDF or text. Kept on this device only.
Keeping your files on this device

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.

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.

My notes on this module

Loading your notes...

Generics, Protocols & ParamSpec — TransformerLab