Lesson · Type Hints & Static Typing
Generics
65 min readGenerics
Generics preserve relationships between input and output types across reusable functions and classes. Type variables, bounds, constraints, and variance describe which substitutions remain sound.
Learning goals
- Explain what a
TypeVarplaceholder means in a signature and how one call pins it to a single type. - Declare a generic class with
Generic[T]and say whatBox[int]versusBox[str]means to a checker. - Read a generic function's signature and deduce the return type from the argument types.
- Choose between a bound and a constraint list for limiting what
Tmay be, and say what each allows. - Explain why a mutable container is invariant, using one assignment the rule refuses to allow.
Mental model
Read a generic signature as a sentence with a pronoun: T means "whatever concrete type this call supplies", and the checker's job is to keep the pronoun pointing at one referent across the whole signature.
Mental model
read it top to bottom
T = TypeVar("T") a placeholder, not a type
generic function: def first(items: list[T]) -> T T is deduced from the arguments
generic class: class Box(Generic[T]) T is fixed by Box[int] at the use site
one rule for both: every occurrence of T in a single call or instance is the same typeCore idea
A generic is a signature with a placeholder: T says "the same type shows up here and there", and the checker fills it from the arguments or from the use-site subscription. Functions and classes are the two places generics appear, and the TypeVar options, bounds and constraint lists, say what may fill the placeholder. Write a generic only when the relationship between several positions is the point; a value that merely has a flexible type does not need one.
Type variables
A type variable such as T = TypeVar("T") is a placeholder the checker fills in from the call: name it in several positions and one call must supply a single consistent type everywhere T appears. It is not a class, and at runtime it has no effect on what the function or class accepts.
Generic classes
A generic class declares one or more type variables in its definition, usually by inheriting Generic[T], so each use such as Box[int] or Box[str] is checked with that substitution. The subscription is a checker-level view: Box[int] and Box[str] name the same runtime class.
Generic functions
A generic function mentions a type variable in its signature, so the checker deduces the type from the arguments and carries it into the return: first(items: list[T]) -> T returns str for a list of strings. The deduction happens statically, and at runtime the function is an ordinary function.
Bounds
A bound such as TypeVar("T", bound=Shape) narrows what may fill T to that class or its subclasses and no further. Because every candidate satisfies the bound, the body may call the bound's methods, and a subclass argument keeps its own subtype through the call.
Constraints
A constraint list such as TypeVar("T", str, bytes) allows only the listed types instead of a hierarchy, and one call must settle on exactly one of them. The difference from a bound is visible on subclasses: a bound keeps the subtype, while a constraint collapses it to the listed type.
Variance intuition
Variance describes how subtype relationships transfer through generic types. Mutable containers are commonly invariant because both reading and writing must remain type-safe.
Walkthrough
T = TypeVar("T")creates the placeholder, and it is not a class at runtime; that is whyBox(42)needs no type argument and the checker infers one from the value.class Box(Generic[T])declares that every box carries one type:number_box = Box(42)deducesT = int, andtext_box = Box("Python")starts a fresh deduction withT = str.def get(self) -> Tties the return type to the same instance type, sonumber_box.get()is anintto the checker andtext_box.get()astr, even though both run the same three lines.- Predict before running: the printed line, what
Box(42).get() + 1is to a checker, and what a checker says aboutnumber_box.value = "text".
Experiments to try
- Add
def set(self, value: T) -> None:toBoxand callnumber_box.set("text"); read the checker complaint and confirm the runtime stays silent. - Write
def first(items: list[T]) -> T:and call it with["a", "b"]and with[1, 2]; state the deducedTfor each call. - Replace the plain
TypeVarwithTypeVar("T", str, bytes)and rerunBox(42); explain what a checker rejects and why the script still runs. - Print
Box[str]andtype(Box[str]), then instantiateBox[str]("x"); separate what the subscription does at runtime from what it means to a checker.
Common mistakes
- Using a type variable in a single position: a placeholder that appears once relates nothing, so the annotation adds noise instead of a relationship; reach for the concrete type or a bound.
- Expecting runtime enforcement:
number_box.value = "text"reassigns the attribute without complaint becauseTexists only in the checker's model. - Overriding deduction with an explicit subscription and ignoring the mismatch:
Box[int]("x")is flagged by a checker but constructs and runs like any other object. - Confusing a bound with a constraint list:
bound=Shapeaccepts every subclass, while a set of listed types admits only those, so choosing the wrong one quietly widens or narrows the API.
Practice: Easy
- Run the worked example, then print
type(number_box),Box[int], andtype(Box[int]); state which of these objects the checker reasons about and which exist at runtime. - Write
def first(items: list[T]) -> T: return items[0]and call it with a list of strings and with a list of ints; write the deducedTfor each call. - Add
set(self, value: T) -> NonetoBoxand show thatnumber_box.set("text")is a checker error whilenumber_box.set(43)is fine.
Practice: Medium
- Define
class Pair(Generic[T]):holding two values with a method returningtuple[T, T]; tryPair(1, "x")and record what the checker infers forT. - Pair a small
class MyInt(int)withTypeVar("A", bound=int)andTypeVar("B", int, str); note that a bound keepsMyIntthrough the call while a constraint collapses it to the listedint. - Write
def swap(pair: tuple[T, T]) -> tuple[T, T]:and show that mixing an int and a string in the tuple is rejected, then rewrite it with two type variables and show the mixed case becomes legal.
Practice: Hard
- Build a
Stack[T]class withpush,pop, andpeekusingGeneric[T]; describe what the checker knows after each operation and name one mixed-type call it rejects. - Failure lab: run
number_box.value = "text", runBox[int]("x"), and write aTthat appears only once in a signature; explain for each why a checker objects or stays silent and why the runtime code runs. - Explain variance with one concrete pair: why
list[int]is not accepted wherelist[float]is wanted even thoughintcan stand in forfloat, and why a read-onlytuple[int, ...]does not have that problem.
Lesson checklist
- I can explain what a
TypeVarplaceholder means in a signature and how one call pins it. - I can declare a generic class or function and describe what the checker deduces at a use site.
- I can choose between a bound and a constraint list and say what each allows.
- I can explain why
Box[int]andBox[str]are the same class at runtime but different types to a checker.
Remember
A generic is a signature with a placeholder: `T` says the same type appears in several positions, and the checker fills it from the arguments or the use-site subscription. Functions deduce `T` from their calls, classes fix it per instance, and the `TypeVar` options, bounds and constraint lists, control what may fill it. Generics are erased at runtime, so their entire effect is the consistency the checker enforces.
Interview angles
What is the main purpose of **Type variables**?+
A type variable such as T = TypeVar("T") is a placeholder the checker fills in from the call: name it in several positions and one call must supply a single consistent type everywhere T appears.
What should you pay attention to when using **Generic classes**?+
A generic class declares one or more type variables in its definition (class Box(Generic[T])), so each Box[int] or Box[str] usage is checked with that substitution. At runtime they name the same class, since the subscription is a checker-level view.
How does **Generic functions** fit into this lesson?+
A generic function mentions a type variable in its signature so the checker deduces it from the arguments and carries it into the return type. first(items: list[T]) -> T returns str for a list of strings, with no runtime machinery involved.
Why does `number_box.value = "text"` run even though a checker rejects it?+
Generics are erased at runtime: the class stores whatever object you assign and never consults T. The checker, which inferred T = int for number_box, is the only thing that objects.