Sub topic 2
Generic functions: relating input and output types
This chapter assumes you can write Python functions and classes, read annotations such as list[int] and str | None, and know that a checker like mypy or pyright reads those annotations without running your code. It uses the Python 3.12 syntax for type parameters.
The problem: losing the type
Suppose you write a function that returns the first item of a sequence. You could annotate it with Any:
from collections.abc import Sequence
from typing import Any
def first_any(items: Sequence[Any]) -> Any:
return items[0]
n = first_any([1, 2, 3]) # checker sees AnyAny turns checking off. The checker no longer knows that n is an int, so it will accept n.upper() without complaint. The annotation says nothing about how the input and output relate, and that relationship is what you want to express.
A type parameter links input and output
A generic function declares a type parameter in square brackets after its name. The checker ties each use of that parameter together within a call.
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
n = first([1, 2, 3]) # checker infers int
s = first(("a", "b")) # checker infers strHere T is a placeholder for one type. At each call, the checker looks at the argument, solves for T, and substitutes it into the return type. For [1, 2, 3], T becomes int, so the result is int. For ("a", "b"), T becomes str.
You never pass T yourself. Inference does it for you.
The same name means the same type
Every occurrence of T in one signature refers to the same type for a given call. This lets you require that two arguments match:
def pick[T](a: T, b: T) -> T:
return a
x = pick(1, 2) # int
y = pick(1, "two") # checker infers a common supertype, such as objectWhen the arguments differ, the checker usually widens T to a type that fits both. This is why pick(1, "two") is not necessarily an error. If you need stricter behavior, use bounds or constraints, which a later chapter covers.
Several type parameters
A function can declare more than one parameter, separated by commas:
def pair_up[K, V](key: K, value: V) -> tuple[K, V]:
return (key, value)
entry = pair_up("age", 30) # tuple[str, int]Each parameter is solved independently. Use a separate parameter whenever two types need not match.
Common errors
- A type parameter used only once. In
def f[T](x: T) -> None,Tlinks nothing. The signature could sayobjectinstead. A type parameter earns its place by appearing at least twice, typically in a parameter and the return type. - Using
Tonly in the return type. Indef make[T]() -> T, the checker has nothing to infer from. Callers get an unsolved type, and the function body cannot honestly produce aT. - Expecting a runtime check. The checker enforces
T, but Python does not. Callingfirston an empty list raisesIndexErrorat runtime, and the annotation does not prevent that. - Using this syntax on Python 3.11 or earlier.
def first[T]is a syntax error before Python 3.12. Older versions useTypeVar, covered in the next chapter.
Exercises
Exercise
Write a generic function last that takes a Sequence and returns its final element, so that last([1.5, 2.5]) is inferred as float.
Show answer
from collections.abc import Sequence def last[T](items: Sequence[T]) -> T: return items[-1] The parameter T appears in both the argument and the return type, so the checker solves T = float for a list of floats.
Exercise
Why is def show[T](x: T) -> None a weak use of a type parameter?
Show answer
T appears only once, so it does not relate any two types. The signature behaves like x: object, and the type parameter adds no information.