Sub topic 12
Writing generic functions with TypeVar
This chapter assumes you can annotate parameters and return values, read list[int] and X | None, run mypy or pyright, and know what Callable and Protocol are. You will learn how a TypeVar lets one function work with many types while keeping the relationship between its input and output types.
The problem: Any throws information away
Suppose you write a function that returns the first element of a sequence. The simplest annotation uses Any:
from typing import Any
def first(items: list[Any]) -> Any:
return items[0]
number = first([1, 2, 3])
# A checker treats `number` as Any, so it accepts number.upper().
# At runtime that line would raise AttributeError.Any turns checking off for every value that flows out of the function. Writing -> int fixes this for one call but breaks the function for strings. You want to say: "whatever element type goes in is the type that comes out." A type variable expresses exactly that.
A basic TypeVar
A TypeVar is a placeholder for a type that the checker fills in separately at each call.
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
return items[0]
number = first([1, 2, 3]) # checker infers int
letter = first("abc") # checker infers str
print(number, letter)Three rules apply:
- The string passed to
TypeVarmust match the variable name. WriteT = TypeVar("T"), notT = TypeVar("X"). Checkers report a mismatch. - The checker solves
Tper call. Infirst([1, 2, 3]),Sequence[T]is matched againstlist[int], soTbecomesint. The return typeTthen becomesint. Thas no meaning outside the function. Two different functions that both useTdo not share a type.
At runtime TypeVar does almost nothing. The interpreter ignores it, as it ignores all hints.
Linking several parameters
The same variable in more than one position forces those positions to agree.
from typing import TypeVar
T = TypeVar("T")
def pick(condition: bool, a: T, b: T) -> T:
return a if condition else b
print(pick(True, 1, 2))
print(pick(False, "x", "y"))If you call pick(True, 1, "y"), the checker has to find one type that fits both arguments. It usually falls back to a common supertype such as object (or int | str in pyright). It will not always report an error. If you want strict agreement, check what your checker infers instead of assuming.
Using more than one TypeVar
Use a separate variable for each independent type. A typical case is a function that transforms items from one type to another:
from collections.abc import Callable
from typing import TypeVar
T = TypeVar("T")
U = TypeVar("U")
def map_list(func: Callable[[T], U], items: list[T]) -> list[U]:
return [func(item) for item in items]
lengths = map_list(len, ["a", "bb", "ccc"]) # list[int]
shouted = map_list(str.upper, ["a", "b"]) # list[str]
print(lengths, shouted)Here T is the input element type and U is the output element type. The checker works out U from the return type of func. This combines the Callable syntax from the previous chapter with generics.
A dictionary helper shows the same idea with keys and values:
from typing import TypeVar
K = TypeVar("K")
V = TypeVar("V")
def invert(mapping: dict[K, V]) -> dict[V, K]:
return {value: key for key, value in mapping.items()}
print(invert({"a": 1, "b": 2}))At runtime this fails if two keys share a value (the later key overwrites the earlier one) or a value is unhashable. The hint does not catch either problem. For stricter use you would bound V to Hashable.
Restricting a TypeVar with bound
An unrestricted T can be anything, so the function body may only do things every object supports. If the body calls <, the checker complains. A bound states that T must be a subtype of some type. You can use a protocol as the bound:
from collections.abc import Sequence
from typing import Any, Protocol, TypeVar
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
T = TypeVar("T", bound=Comparable)
def largest(items: Sequence[T]) -> T:
best = items[0]
for item in items[1:]:
if best < item:
best = item
return best
print(largest([3, 1, 2]))
print(largest(["pear", "apple"]))largest returns exactly the element type it received. With a bound, passing a list[int] gives back int, not Comparable. Passing a list of objects with no __lt__ is reported as an error.
Restricting a TypeVar with constraints
You can instead list the exact types allowed:
from typing import TypeVar
S = TypeVar("S", str, bytes)
def double(value: S) -> S:
return value + value
print(double("ab"))
print(double(b"ab"))The checker verifies the body once for each listed type. This suits functions that behave differently for a few unrelated types, as re and os.path functions do with str and bytes.
| Feature | `bound=X` | Constraints `(A, B)` |
|---|---|---|
| Accepts | `X` and any subclass | Only the listed types |
| Result for a subclass | The subclass itself | The listed type it matches |
| Body is checked | Once, against `X` | Once per listed type |
| Typical use | "Anything with this capability" | "Either `str` or `bytes`, never mixed" |
The subclass row matters. If class Meters(int) is passed to a function constrained to int and float, the result is typed int, so the Meters information is lost. Prefer bound unless the body truly needs a separate check per type.
The Python 3.12 syntax
From Python 3.12 you can declare type parameters directly on the function, with no separate TypeVar statement:
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
def largest_int[T: int](items: Sequence[T]) -> T:
return max(items)
print(first(["a", "b"]), largest_int([4, 9]))[T] declares an unbounded variable and [T: int] declares a bound. The variable is scoped to that function. This code needs Python 3.12 or newer. For older versions, or libraries that support them, keep using TypeVar.
Common errors
- A TypeVar that appears only once. In
def log(item: T) -> None,Tlinks nothing. Checkers may warn, and the simpleritem: objectoritem: Anysays the same thing. - Returning a value that is not
T. Indef first(items: Sequence[T]) -> T: return 0, the checker reports thatintis notT. The function must return something derived from itsTinputs. - Using
Twhere a concrete type is needed. Inside an unbounded generic function you cannot call.upper()on aT. Add a bound or narrow withisinstance. - Expecting runtime enforcement.
first(5)still fails only whenitems[0]runs. Type variables never check anything at runtime.
Exercise
Write a function last that returns the last element of any sequence, with a signature that makes a checker infer str for last(["a", "b"]) and int for last((1, 2, 3)).
Show answer
from collections.abc import Sequence from typing import TypeVar T = TypeVar("T") def last(items: Sequence[T]) -> T: return items[-1] The variable T links the element type of the argument to the return type. Both a list and a tuple are Sequences, so T binds to str in the first call and int in the second.
Exercise
Why is def total(a: T, b: T) -> T: return a + b rejected by a checker, and how would you fix it?
Show answer
An unbounded T could be any type, and not every type supports +, so the checker cannot verify the body. Fix it by adding a bound or constraints that guarantee the operation, for example T = TypeVar("T", int, float, str), or a bound to a Protocol that defines _add_.