TypeVar bound restricts the type to subclasses of a specific type.
1from typing import TypeVar23# Bounded TypeVar4Number = TypeVar("Number", bound=int)56def double(value: Number) -> Number:7 return value * 289double(5) # OK — int is bound10double(3.14) # OK — float is subclass of Number11# double("hello") # Error — str is not a Number1213# Without bound — any type14T = TypeVar("T")1516def identity(value: T) -> T:17 return value1819identity(5) # OK20identity("hello") # OK2122# With constraints (only these types)23StrOrInt = TypeVar("StrOrInt", str, int)2425def process(value: StrOrInt) -> StrOrInt:26 return value2728process(5) # OK29process("hello") # OK30# process(3.14) # Error — float not allowed3132# Complex bound33from abc import ABC3435class Shape(ABC):36 def area(self) -> float: ...3738ShapeType = TypeVar("ShapeType", bound=Shape)3940def calculate_area(shape: ShapeType) -> float:41 return shape.area()
When to use: