Sub topic 6
Bounds and constraints
This chapter assumes you can read basic generic functions such as def first[T](items: Sequence[T]) -> T. It also assumes you know that mypy or pyright checks annotations without running your program. Examples use the Python 3.12 syntax, and the legacy TypeVar forms appear alongside for older code.
The problem: an unrestricted T knows nothing
An unrestricted type parameter stands for any type, so the checker only lets you do what every object supports. This function is rejected:
def longest[T](a: T, b: T) -> T:
return a if len(a) >= len(b) else b # error: T has no len()You want to say "any type, as long as it has a length". Python gives you two tools for restricting a type parameter. A bound sets a ceiling in a type hierarchy. Constraints list the only allowed types. They look similar but behave differently.
Upper bounds
An upper bound is written with a colon after the parameter name. The argument type must be the bound or a subtype of it.
from collections.abc import Sized
def longest[T: Sized](a: T, b: T) -> T:
return a if len(a) >= len(b) else bInside the body, the checker treats T as "something that is at least Sized", so len() is allowed. At each call site, the checker solves T to the actual argument type, not to the bound:
longest([1, 2], [3]) # T is list[int], result is list[int]
longest("ab", "abc") # T is str, result is str
longest(5, 6) # error: int is not SizedThis is the main benefit of a bound over a plain annotation. If you wrote def longest(a: Sized, b: Sized) -> Sized, the result would be Sized and you would lose the fact that it is a str.
Bounds with your own classes
class Animal:
def name(self) -> str:
return "animal"
class Dog(Animal):
def fetch(self) -> str:
return "ball"
def loudest[T: Animal](a: T, b: T) -> T:
return a if len(a.name()) >= len(b.name()) else b
loudest(Dog(), Dog()).fetch() # fine: the result is Dog, not AnimalIf you pass one Dog and one Animal, the checker solves T to the closest common type, Animal. The result is then Animal, and calling .fetch() on it is an error.
Bounds with protocols
A bound is often a protocol, which describes behavior instead of a class. This lets you require a capability without forcing inheritance.
from typing import Any, Protocol
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
def smallest[T: Comparable](items: list[T]) -> T:
result = items[0]
for item in items[1:]:
if item < result:
result = item
return result
print(smallest([3, 1, 2])) # 1
print(smallest(["b", "a", "c"])) # aBoth int and str satisfy Comparable structurally, so no registration is needed. The next chapters cover protocols in more depth.
Constraints
Constraints are written as a parenthesized tuple of types. The parameter must be exactly one of them in each call.
def add[T: (int, str)](a: T, b: T) -> T:
return a + badd(1, 2) # fine: T is int
add("a", "b") # fine: T is str
add(1, "b") # error: no single constraint fits both arguments
add(1.5, 2.5) # error: float is neither int nor strA constraint list needs at least two types. A single type is a bound written the long way, and checkers reject the one-element form.
How the body is checked
For a constrained parameter, the checker verifies the function body once for each constraint. Here that means once with T as int and once with T as str. a + b is valid in both, so the function passes. If the body used a.upper(), it would fail for the int case, even though str supports it.
Subtypes collapse to the constraint
When you pass a subtype of a constraint, the checker solves T to the constraint itself, not to the subtype.
add(True, False) # bool is a subtype of int, so T is int and the result is intWith a bound, the result would keep the more precise type. With constraints, you always get back one of the listed types. This is the most surprising difference between the two tools, and it is why constraints suit functions whose behavior really differs per type.
Bound or constraints?
| Question | Upper bound `T: X` | Constraints `T: (A, B)` |
|---|---|---|
| Which argument types are allowed? | `X` and any subtype | Only `A` or `B` (and their subtypes) |
| What does `T` solve to? | The actual argument type | Exactly `A` or `B` |
| How is the body checked? | Once, assuming `T` is `X` | Once per constraint |
| Typical use | "Anything with this capability" | "These specific types, behaving differently" |
Prefer a bound unless you have a reason not to. Constraints are rarely needed. A common alternative to constraints is a bound on a union, but it behaves differently:
def add_loose[T: int | str](a: T, b: T) -> T:
return a + b # error: int + str is not valid when T is int | strHere T may solve to int | str, so the checker must accept the case where a is an int and b is a str. Constraints rule that case out, because T must be one type from the list.
Inspecting bounds at runtime
The 3.12 syntax creates real TypeVar objects, and they record what you declared. A function's __type_params__ tuple holds them.
from collections.abc import Sized
def longest[T: Sized](a: T, b: T) -> T:
return a if len(a) >= len(b) else b
def add[T: (int, str)](a: T, b: T) -> T:
return a + b
(t,) = longest.__type_params__
print(t.__name__, t.__bound__) # T <class 'collections.abc.Sized'>
(u,) = add.__type_params__
print(u.__constraints__) # (<class 'int'>, <class 'str'>)
print(u.__bound__) # None
print(add(1.5, 2.5)) # 4.0The last line runs without error. Python stores bounds and constraints but never enforces them. Only the static checker rejects add(1.5, 2.5).
Lazy evaluation of bounds
In the 3.12 syntax, bounds and constraints are evaluated lazily. They are not computed when the function or class is defined. They are computed the first time you read __bound__ or __constraints__. This means a bound can refer to a name defined later without quotes:
def clone[T: Node](item: T) -> T:
return item
class Node:
pass
(t,) = clone.__type_params__
print(t.__bound__) # <class '__main__.Node'>The legacy form evaluates its arguments immediately, so a forward reference needs a string.
Legacy syntax
Before 3.12, you pass the bound or constraints to TypeVar:
from collections.abc import Sized
from typing import TypeVar
S = TypeVar("S", bound=Sized)
N = TypeVar("N", int, str)
def longest(a: S, b: S) -> S:
return a if len(a) >= len(b) else b
def add(a: N, b: N) -> N:
return a + b| Meaning | Legacy | Python 3.12+ |
|---|---|---|
| Upper bound | `TypeVar("T", bound=Sized)` | `[T: Sized]` |
| Constraints | `TypeVar("T", int, str)` | `[T: (int, str)]` |
| Forward reference | `bound="Node"` (string) | `[T: Node]` (lazy) |
Common errors
- Using the bound's methods on a constrained type. The body is checked per constraint, so a method that exists on only one constraint fails.
- Expecting a constrained function to keep subtypes.
add(True, False)isint, notbool. Use a bound if the subtype matters. - Writing one constraint.
T: (int,)is an error. UseT: int. - Using another type parameter in a bound. A bound such as
T: list[U]is not allowed, because bounds cannot contain type variables. Use a protocol or restructure the signature. - Assuming runtime checks. Calling
add(1.5, 2.5)runs fine. Run the checker to catch it. - Confusing a bound with a union bound.
T: int | straccepts mixed pairs, whileT: (int, str)does not.
Exercises
Exercise
Why does def biggest[T](a: T, b: T) -> T: return a if a > b else b fail type checking, and how do you fix it so that biggest(3, 7) is typed as int?
Show answer
An unrestricted T guarantees no operations, so > is not allowed. Add a bound that provides the capability, for example a protocol with __lt__ or __gt__: class SupportsGT(Protocol): def __gt__(self, other: Any, /) -> bool: ... and def biggest[T: SupportsGT](a: T, b: T) -> T. Because it is a bound, T solves to the argument type, so biggest(3, 7) is int.
Exercise
Given def add[T: (int, str)](a: T, b: T) -> T, what type does a checker give add(True, False), which calls with two bool values, and why? Would a bound T: int give the same answer?
Show answer
It gives int. With constraints, a subtype of a constraint is solved to the constraint itself, so bool becomes int. With the bound T: int, T would solve to bool, so the result would be bool.
Exercise
What does add.__type_params__[0].__bound__ return for def add[T: (int, str)](a: T, b: T) -> T, and what does add(1.5, 2.5) do when the program runs?
Show answer
__bound__ is None, because constraints are stored in __constraints__, which holds (int, str). add(1.5, 2.5) runs and returns 4.0. Python does not enforce constraints, so only a static type checker reports the error.