Sub topic 2
Generic functions: relating input and output types
This chapter assumes you know Python functions and classes, can read annotations such as list[int] and str | None, and have run a static type checker such as mypy or pyright. The examples use the Python 3.12 syntax def f[T](...), so they need Python 3.12 or newer. Older Python versions use a different spelling, which the next chapter covers.
The problem: losing information with Any
Suppose you write a function that returns the first element of a sequence. The simplest annotation is Any:
from typing import Any
def first(items: list[Any]) -> Any:
return items[0]
n = first([1, 2, 3])
n.upper() # no error from the checker, crashes at runtimeAny turns off checking. The checker cannot know that a list of integers produces an integer, so it accepts n.upper() and the mistake only shows up when the program runs.
You could write -> int | str | float instead, but then every caller must narrow the result before using it. What you want to say is: "the return type is whatever the element type of the argument is." A generic function says exactly that.
Declaring a type parameter
A type parameter is a placeholder for a type that the checker fills in at each call. You declare it in square brackets after the function name:
from collections.abc import Sequence
from typing import reveal_type
def first[T](items: Sequence[T]) -> T:
return items[0]
n = first([1, 2, 3])
s = first(("a", "b"))
reveal_type(n) # checker reports: int
reveal_type(s) # checker reports: strT is only a name. By convention it is a single capital letter, or a short descriptive name such as Item. The brackets introduce T for this function only, so it does not exist outside the function and you do not need to import anything.
Read the signature as "for any type T, take a Sequence of T and return a T." The same letter in two places is the constraint. If you used two different names, the checker would treat the input and output types as unrelated.
reveal_type is a helper that typing provides from Python 3.11. At runtime it prints the value's type to standard error and returns its argument. Static checkers treat it specially and report the inferred type. You will use it to see what the checker decided.
How the checker solves for T
At each call the checker performs inference. It looks at the argument types, finds the T that makes them fit the parameter types, and substitutes that T into the return type.
Each call is solved separately. The call first([1, 2, 3]) solves T = int, and the next call first(("a", "b")) solves T = str. The function definition itself is written once.
Inside the body, the checker treats T as an unknown type. You can index the sequence and return an element, because those operations work for any element type. You cannot call items[0].upper(), because nothing says T supports upper. Restricting what T can be is the subject of a later chapter on bounds.
What the checker reports
A generic signature lets the checker catch mistakes that Any would hide:
def first[T](items: list[T]) -> T:
return items[0]
n = first([1, 2, 3])
n.upper() # error: "int" has no attribute "upper"
first(5) # error: "int" is not a listBoth errors come from the signature alone, and the function body is not involved.
Several uses of the same T
When T appears in more than one parameter, the checker must find one type that fits all of them.
from typing import reveal_type
def pick[T](a: T, b: T, use_first: bool) -> T:
return a if use_first else b
x = pick(1, 2, True)
reveal_type(x) # int
y = pick(1, "two", True)
reveal_type(y) # pyright: int | str, mypy: objectWith two int arguments the answer is int. With an int and a str, the checker widens T to a type that covers both. Pyright builds the union int | str. Mypy computes a common supertype and reports object. Neither is an error, but the result is rarely useful, so a call like this usually signals a bug in the caller. The exact choice depends on the checker and its version, so do not rely on it.
Several type parameters
Separate the parameters with commas when the types are independent:
from collections.abc import Sequence
def pair_up[K, V](keys: Sequence[K], values: Sequence[V]) -> dict[K, V]:
return dict(zip(keys, values, strict=True))
ages = pair_up(["ana", "bo"], [31, 27]) # dict[str, int]K and V are solved independently, so the result is dict[str, int]. If you had used one T for both, the call would have widened it to str | int and lost the distinction.
Generic functions that take callables
Type parameters can also relate a function's input type to a callback's types:
from collections.abc import Callable, Iterable
def map_list[T, U](func: Callable[[T], U], items: Iterable[T]) -> list[U]:
return [func(item) for item in items]
lengths = map_list(len, ["a", "bcd"]) # list[int]
shouted = map_list(str.upper, ["a", "bcd"]) # list[str]The checker reads T from the callback's parameter and the iterable's element type, which must agree. It reads U from the callback's return type. Passing str.upper with a list of integers would be an error, because T cannot be both str and int.
Type parameters inside annotations of the body
A type parameter is available to every annotation in the function, including local variables:
def last_two[T](items: list[T]) -> list[T]:
result: list[T] = items[-2:]
return resultThis is useful when a local variable has no obvious initial value, such as an empty list that you fill later.
Expected types and return-only parameters
Usually the checker solves T from the arguments. If T appears only in the return type, there is nothing to solve from, and the checker may use the type that the surrounding context expects:
def empty[T]() -> list[T]:
return []
nums: list[int] = empty() # T = int, taken from the annotation
oops = empty() # checker cannot infer T; mypy asks for an annotationWithout the annotation on oops, mypy reports "Need type annotation". Pyright infers list[Unknown], which behaves like Any and is reported only in strict mode.
This does not extend to returning a bare T. A signature like def make[T]() -> T promises to return any type the caller wants, and the body cannot honor that. Checkers flag the body, because it must return some specific value that is not necessarily a T.
Mistakes to avoid
A type parameter that appears only once in a signature is usually pointless. This function has no relation to express:
def describe[T](item: T) -> str:
return repr(item)The caller gets the same result as with item: object, and the signature is harder to read. Use a type parameter when it links at least two places, such as a parameter and the return type, or two parameters. Pyright can report a single-use parameter in strict mode.
The next mistake is expecting runtime behavior. The checker infers T, but nothing in the running program records it. The call first([1, 2, 3]) does not check that the items are integers, and you cannot write first[int](...) to select a type, because a function object does not support subscripting. To force a type, annotate a variable or the argument, for example first(list[int]()).
Finally, inference keeps the general type, not the literal. The call first([1, 2, 3]) yields int, not Literal[1]. If you need the exact literal types, you must say so with a more specific annotation.
When to reach for a generic function
Use a generic function when the output type depends on the input type and a single concrete annotation would be too narrow or too loose. Typical cases:
- Containers and accessors, such as
first,last, orget_or_default. - Transformations, such as
map_listor a function that sorts any list of comparable items. - Identity-like helpers that return their argument, such as
def keep[T](x: T) -> T.
If the function works with one fixed type, or the output type never depends on the input type, a plain annotation is simpler.
Exercise
What type does a checker infer for result in this code, and why?
def swapfirst[T](items: list[T], new: T) -> T:
old = items[0]
items[0] = new
return old
result = swapfirst([1.5, 2.5], 3.0)
Show answer
It infers float. The call fits both parameters with T = float, because list[float] supplies T and 3.0 is also a float. The return type T then becomes float.
Exercise
Write a generic function second_or_default that takes a Sequence of items and a default value of the same element type, and returns the second item, or the default if the sequence has fewer than two items. Give its signature.
Show answer
def secondordefault[T](items: Sequence[T], default: T) -> T:
return items[1] if len(items) > 1 else default
The same T in items and default forces the default to match the element type, and the return type T gives callers that same type. The function needs from collections.abc import Sequence.