What problem does a generic function or class with `TypeVar` (or the newer `class Stack[T]:` syntax) solve?
Answer
A generic lets a function or class be written once while still preserving a precise relationship between its input and output types for the type checker, rather than falling back to an unhelpful `Any` that discards type information entirely. `def first(items: list[T]) -> T:` tells the checker that whatever concrete type fills the list, the return value is that same type — passing `list[int]` gets back `int`, passing `list[str]` gets back `str` — which `Any` could never express. Python 3.12's PEP 695 syntax, `def first[T](items: list[T]) -> T:`, expresses the same idea without a separate `TypeVar` declaration.
Strong answer includes
- preserves a precise input-output type relationship instead of falling back to Any
- the same type variable ties multiple positions together across calls
- PEP 695 (3.12) syntax expresses the same idea without a separate TypeVar
Practical example
class Stack[T]:
def push(self, item: T) -> None: ...
def pop(self) -> T: ...guarantees a checker flags
Stack[int]().push("oops")as an error, something an untyped or `Any` -typed stack could never catch.