Skip to main content
A bound TypeVar is a generic type variable that restricts its permissible types to a specific base type and its subtypes. By defining an upper bound, the static type checker guarantees that any type assigned to the variable conforms to the interface of the bounding type, while strictly preserving the specific subclass type through the generic operation.

Syntax

Legacy Syntax (Python 3.11 and older): Using the typing module, the bound keyword argument accepts a single type (a class, a Union, or another type construct).
Modern Syntax (Python 3.12+ / PEP 695): Python 3.12 introduced native generic syntax using type parameter lists. A bound is denoted using a colon (:) after the type variable name.

Type Resolution Mechanics

When a type checker evaluates a bound TypeVar, it performs two primary operations:
  1. Validation: It verifies that the concrete type provided at the call site is a subtype of the bound (e.g., issubclass(ConcreteType, BaseType)). If it is not, a type error is emitted.
  2. Type Preservation: Unlike a standard type hint (which upcasts the type to the base class), a bound TypeVar binds to the exact subclass provided.

Bound vs. Constrained TypeVars

It is critical to distinguish a bound TypeVar from a constrained TypeVar.
  • Bound (bound=BaseType): Establishes an upper limit in the inheritance tree. It accepts the base type and an infinite number of potential subclasses. The type checker resolves T to whatever specific subclass is passed.
  • Constrained (TypeVar('T', TypeA, TypeB)): Restricts the variable to an exact, finite list of types. Subclasses of TypeA or TypeB are evaluated strictly as TypeA or TypeB.

Forward References in Bounds

If the bounding type is not yet defined when the TypeVar is declared, the bound argument accepts a string literal representing the forward reference. To be valid and provide type-checking utility, the type variable must establish a relationship by appearing at least twice in a signature (e.g., linking an argument type to a return type) or be used to define a Generic class.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More