Sub topic 12
Writing generic functions with TypeVar
This chapter assumes you can annotate parameters and return values, use built-in generics such as list[int], and run mypy or pyright on a file.
The problem: losing the type
Suppose you write a function that returns the first item of a sequence. You could annotate it with Any, but then the checker forgets what the sequence held.
from typing import Any
def first_any(items: list[Any]) -> Any:
return items[0]
value = first_any([1, 2, 3]) # the checker treats value as AnyAny method call on value passes the checker, even a wrong one. You want the return type to follow the input type.
Linking types with TypeVar
A TypeVar is a placeholder for a type. Every use of the same TypeVar in one signature must refer to the same type, and the checker works out which type that is 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])
letter = first("abc")
reveal_type(number) # checker output: int
reveal_type(letter) # checker output: strreveal_type is understood by mypy and pyright. Do not run that line as plain Python on versions before 3.11, because the name does not exist at runtime. Remove it, or import it from typing on 3.11 and later.
The name string in TypeVar("T") must match the variable name. Use Sequence[T] rather than list[T] here, because it also accepts tuples and strings.
How the checker resolves T
Each call is solved on its own. T is int in one call and str in the other, and neither affects the other.
Constraining a TypeVar
Sometimes the function needs to do something with the value, such as compare it. An unrestricted T allows any type, so the checker rejects operations that not every type supports. You can restrict it in two ways.
bound=accepts a type and any subtype of it. The result keeps the subtype.- Listing types accepts only those exact choices.
from typing import TypeVar
Number = TypeVar("Number", int, float)
def double(value: Number) -> Number:
return value * 2
print(double(4))
print(double(2.5))
class Animal:
def name(self) -> str:
return "animal"
class Dog(Animal):
def name(self) -> str:
return "dog"
A = TypeVar("A", bound=Animal)
def loudest(animals: list[A]) -> A:
return animals[0]
dog = loudest([Dog()]) # the checker infers Dog, not Animal
print(dog.name())With bound=Animal, passing a list of Dog returns a Dog. Annotating the function with plain Animal would return Animal and lose that detail.
Common mistakes
- Using a
TypeVaronly once in a signature.def f(x: T) -> Nonegains nothing overobject, because nothing links it to another type. - Mixing
Twith unrelated types and expecting a link. Only repeated use of the same variable ties types together. - Treating a constrained
TypeVaras a union.Numberisintorfloatfor a whole call, never a mix of both.
Exercise
Write a generic function last that takes a Sequence[T] and returns its final item. What type should a checker infer for last(["a", "b"]), and why is Sequence[T] -> T better than Sequence[Any] -> Any?
Show answer
def last(items: Sequence[T]) -> T: return items[-1], with T = TypeVar("T"). The checker infers str, because T is bound to the element type of the argument. With Any, the result would be Any, so the checker could not catch misuse of the returned value.