Python Type Hints: Generics, Protocols, and TypeVar Explained
Type hints go beyond annotating parameters. Generics, Protocols, and TypeVar let you express complex type relationships. Here is how. Basic type annotations. str , int , list[int] . cover most function signatures. But they cannot express relationships like 'this function returns the same type it receives' or 'this container works with any type, consistently.' For those, Python has generics, TypeVar , and Protocol . They add expressiveness that catches real bugs in generic utilities and library code. TypeVar for Type Relationships A TypeVar is a type variable. a placeholder for a type that is determined at each call site. The simplest use is a function that returns the same type it receives. from typing import TypeVar T = TypeVar('T') def first(items: list[T]) -> T: return items[0] # T is inferred as int result: int = first([1, 2, 3]) # T is inferred as str result: str = first(['a', 'b', 'c']) Without TypeVar , the return type would have to be a broad type like Any or object , losing type safety. With it, the type checker tracks the relationship and knows that first([1, 2, 3]) returns an int .…