Sub topic 6
Bounds and constraints
This chapter assumes you can write generic functions and classes with the Python 3.12 syntax (def f[T], class C[T]) and that you run a static checker such as mypy or pyright. An unrestricted type parameter lets the checker assume almost nothing about T. Bounds and constraints give it more to work with.
Why an unrestricted T is limiting
Inside a generic function, a plain T is treated as object. The checker rejects any operation that not every object supports.
def longest[T](a: T, b: T) -> T:
return a if len(a) >= len(b) else b # error: T has no __len__You can restrict T in two ways: with an upper bound or with a set of constraints.
Upper bounds
An upper bound says that T must be a subtype of a given type. You write it after a colon.
from collections.abc import Sized
def longest[T: Sized](a: T, b: T) -> T:
return a if len(a) >= len(b) else b
print(longest("abc", "de")) # abc
print(longest([1, 2], [3])) # [1, 2]Sized is a protocol with a __len__ method, so len() is now allowed on a and b. The return type is still T, not Sized. A call with two str arguments gives back a str, so the checker keeps the precise type.
The pre-3.12 spelling uses a keyword argument: T = TypeVar("T", bound=Sized).
Constraints
Constraints list the exact types that T may be. You write them as a parenthesized tuple.
def add[T: (int, str)](a: T, b: T) -> T:
return a + b
add(1, 2) # fine, T is int
add("a", "b") # fine, T is str
add(1, "b") # error: T cannot be both int and strThe checker type-checks the function body once for each listed type. a + b is valid for int and for str, so the body passes. The pre-3.12 spelling is TypeVar("T", int, str).
Bound versus constraints
The two forms behave differently for subclasses. Take a subclass of int:
class MyInt(int):
pass
def keep_bound[T: int](x: T) -> T:
return x
def keep_constrained[T: (int, str)](x: T) -> T:
return x
reveal_type(keep_bound(MyInt(1))) # MyInt
reveal_type(keep_constrained(MyInt(1))) # intWith a bound, the checker keeps the argument's own type. With constraints, it picks the matching constraint, so a MyInt comes back as int.
| Feature | Bound (`T: X`) | Constraints (`T: (X, Y)`) |
|---|---|---|
| Accepts | `X` and any subtype | Only `X` or `Y` |
| Subclass argument | Result keeps the subclass | Result becomes the constraint |
| Body is checked | Once, against `X` | Once per listed type |
| Mixed arguments | Allowed if all fit `X` | Not allowed in one call |
Common errors
- Using one constraint.
T: (int)is justT: intwith parentheses, so it is a bound. Constraints need at least two types. - Expecting a union.
T: int | stris a bound, soadd(1, "b")would be accepted, buta + bfails inside the body. Use a constraint tuple when each call must pick one type. - Returning the bound instead of
T.def f[T: Sized](x: T) -> Sizedthrows away the precise type the caller passed in.
Exercise
Write a function biggest that takes two arguments of the same type and returns the larger one with >. Which restriction would you use for T, and why would T: (int, str) be a poor fit?
Show answer
Use a bound on a comparable type, for example def biggest[T: float](a: T, b: T) -> T: return a if a > b else b, or a bound on a custom protocol that defines __gt__. T: (int, str) allows only those two types, so it rejects float, Decimal, and user classes with ordering, and it returns plain int for an int subclass. A bound accepts any subtype and keeps its type in the result.
Exercise
A checker accepts f(MyInt(1)) for def f[T: (int, str)](x: T) -> T. What type does it infer for the result, and what would it be if T were declared as T: int?
Show answer
With constraints it infers int, the matching constraint. With the bound T: int it infers MyInt.