Sub topic 2
Python Generics and the Type Parameter Syntax
Assume you know functions, classes, annotations such as list[int], and static type checkers such as mypy or pyright. Python 3.12 adds a shorter way to declare type parameters. A type parameter is a placeholder that a checker replaces with a specific type.
The type parameter syntax from Python 3.12
Use square brackets after a function or class name:
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
number = first([1, 2, 3]) # inferred as int
word = first(("a", "b")) # inferred as str
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
def get(self) -> T:
return self.valueThe same T connects the argument and return types. Box[int] describes a box whose value is an integer.
Before Python 3.12, write the equivalent with TypeVar and Generic:
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T) -> None:
self.value = valueThe newer syntax keeps the type parameter close to the definition.
Bounds and constraints
A bound requires a type to support a particular interface. A constraint limits it to listed choices.
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 + bT: Sized allows len() because every permitted type implements Sized. The constrained function accepts int or str, but not an arbitrary type.
Variance and automatic variance inference
Variance describes safe substitution between related generic types. Covariance is safe for read-only values. A checker can infer it with the new syntax:
class ReadOnlyBox[T]:
def __init__(self, value: T) -> None:
self._value = value
def get(self) -> T:
return self._valueA checker may allow ReadOnlyBox[int] where ReadOnlyBox[float] is expected. A publicly writable value usually makes a generic class invariant, because callers could insert an incompatible value.
Generic type aliases with `type`
The type statement defines reusable aliases:
type Pair[T] = tuple[T, T]
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
def swap[T](pair: Pair[T]) -> Pair[T]:
return pair[1], pair[0]Type aliases describe types only. They do not create runtime classes.
Exercise
Should a function use a bound or a constraint when it accepts any object with a __len__ operation?
Show answer
Use a bound, such as T: Sized, because the requirement is a capability rather than a fixed list of types.