Generics with type parameter syntax (PEP 695)

suggest change

A generic function or class works with many types while keeping track of which type it was given. first(xs) returns an int for a list of ints and a str for a list of strings. Before Python 3.12 you described this with a module-level TypeVar object, as shown in Generic Types:

from typing import TypeVar

T = TypeVar("T")

def first(xs: list[T]) -> T:
    return xs[0]

PEP 695 (Python 3.12) added dedicated syntax. You declare type parameters in square brackets right after the function or class name:

def first[T](xs: list[T]) -> T:
    return xs[0]

The new syntax:

PEP 696 (Python 3.13) added defaults for type parameters (class Box[T = int]).

This article covers generic functions and classes, bounds and constraints, variance, the type statement and defaults. For each feature the old TypeVar spelling is shown as well, because you will still see it in existing code. Runtime examples were run with Python 3.13.15. Type checker output comes from mypy 2.4.0 and pyright 1.1.414.

Generic functions

Put the type parameters in square brackets between the function name and the argument list:

def first[T](xs: list[T]) -> T:
    return xs[0]

print(first([3, 1, 2]))
print(first(["a", "b"]))
print(first.__type_params__)
3
a
(T,)

At runtime type hints do nothing: first is an ordinary function. The new syntax creates a real TypeVar object and stores it in the function's __type_params__ attribute.

The benefit shows up in a type checker. It solves T from the arguments at each call site:

from typing import reveal_type

def first[T](xs: list[T]) -> T:
    return xs[0]

n = first([3, 1, 2])
s = first(["a", "b"])
reveal_type(n)
reveal_type(s)
s.upper()
n.upper()
$ mypy first.py
first.py:8: note: Revealed type is "int"
first.py:9: note: Revealed type is "str"
first.py:11: error: "int" has no attribute "upper"  [attr-defined]
Found 1 error in 1 file (checked 1 source file)

A function can have several type parameters, separated by commas. Here T is the item type and K is the key type:

from collections.abc import Callable, Iterable

def group_by[T, K](items: Iterable[T], key: Callable[[T], K]) -> dict[K, list[T]]:
    groups: dict[K, list[T]] = {}
    for item in items:
        groups.setdefault(key(item), []).append(item)
    return groups

print(group_by(["apple", "avocado", "banana", "cherry"], key=lambda s: s[0]))
{'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['cherry']}

Called as group_by([1, 2, 3], key=lambda n: n % 2 == 0), the result type is dict[bool, list[int]].

Generic classes

The same brackets go after the class name. Inside the class body T can be used in attribute annotations and in method signatures:

class Stack[T]:
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

    def __len__(self) -> int:
        return len(self._items)

s = Stack[int]()
s.push(1)
s.push(2)
print(s.pop(), len(s))

print(Stack.__type_params__)
print(Stack.__mro__)
print(Stack[int])
2 1
(T,)
(<class '__main__.Stack'>, <class 'typing.Generic'>, <class 'object'>)
__main__.Stack[int]

class Stack[T] adds typing.Generic to the bases for you. The old spelling requires you to write it out:

from typing import Generic, TypeVar

T = TypeVar("T")

class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

Specify the type argument either explicitly (Stack[int]()) or through the annotation of the variable you assign to:

from typing import reveal_type

class Stack[T]:
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

ints = Stack[int]()
ints.push(1)
ints.push("two")
reveal_type(ints.pop())

names: Stack[str] = Stack()
reveal_type(names)
$ mypy stack.py
stack.py:15: error: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int"  [arg-type]
stack.py:16: note: Revealed type is "int"
stack.py:19: note: Revealed type is "stack.Stack[str]"
Found 1 error in 1 file (checked 1 source file)

Generic methods and subclassing

A method can declare its own type parameters in addition to the class's. Below, K and V belong to the class, and R belongs only to map_value. You can also subclass a generic class, including built-in ones such as list:

from collections.abc import Callable

class Pair[K, V]:
    def __init__(self, key: K, value: V) -> None:
        self.key = key
        self.value = value

    def map_value[R](self, fn: Callable[[V], R]) -> "Pair[K, R]":
        return Pair(self.key, fn(self.value))

    def __repr__(self) -> str:
        return f"Pair({self.key!r}, {self.value!r})"

p = Pair("pi", 3.14159)
print(p.map_value(round))
print(Pair.map_value.__type_params__)

class NamedStack[T](list[T]):
    def __init__(self, name: str) -> None:
        super().__init__()
        self.name = name

ns = NamedStack[int]("ids")
ns.append(5)
print(ns.name, ns)
Pair('pi', 3)
(R,)
ids [5]

mypy infers Pair[str, float] for p and Pair[str, int] for p.map_value(round).

The return annotation "Pair[K, R]" is quoted because in Python 3.13 and older, annotations are evaluated when the def runs, and at that point the name Pair doesn't exist yet. Without the quotes you get NameError: name 'Pair' is not defined. Python 3.14 evaluates annotations lazily, so the quotes are no longer needed there.

Bounds and constraints

An unrestricted T can be any type, so inside the function you can only do what works on every object. There are two ways to restrict it.

An upper bound ([T: SomeType]) accepts SomeType or any subtype of it, and the checker keeps the exact subtype. Constraints ([T: (A, B)], a tuple of at least two types) accept exactly one of the listed types. The checker solves T to one of them, not to a subtype:

from collections.abc import Hashable, Sequence
from typing import reveal_type

class Animal:
    def speak(self) -> str:
        return "..."

class Dog(Animal):
    def speak(self) -> str:
        return "Woof"

class UserId(str): ...

def loudest[A: Animal](animals: list[A]) -> A:
    return max(animals, key=lambda a: len(a.speak()))

def dedupe[H: Hashable](xs: Sequence[H]) -> list[H]:
    return list(dict.fromkeys(xs))

def keep_bound[S: str](s: S) -> S:
    return s

def concat[S: (str, bytes)](a: S, b: S) -> S:
    return a + b

reveal_type(loudest([Dog(), Dog()]))
reveal_type(keep_bound(UserId("u1")))
reveal_type(concat(UserId("u1"), "cd"))
loudest([1, 2])
dedupe([[1], [2]])
concat("ab", b"cd")
$ mypy bounds.py
bounds.py:26: note: Revealed type is "bounds.Dog"
bounds.py:27: note: Revealed type is "bounds.UserId"
bounds.py:28: note: Revealed type is "str"
bounds.py:29: error: Value of type variable "A" of "loudest" cannot be "int"  [type-var]
bounds.py:30: error: Value of type variable "H" of "dedupe" cannot be "list[int]"  [type-var]
bounds.py:31: error: Value of type variable "S" of "concat" cannot be "Sequence[object]"  [type-var]
Found 3 errors in 1 file (checked 1 source file)

Note the results:

pyright explains the last error more directly:

bounds.py:31:14 - error: Argument of type "Literal[b"cd"]" cannot be assigned to parameter "b" of type "S@concat" in function "concat"
    "Literal[b"cd"]" is not assignable to "str" (reportArgumentType)

The bound and the constraints are available on the type parameter at runtime:

from collections.abc import Hashable, Sequence

def dedupe[H: Hashable](xs: Sequence[H]) -> list[H]:
    return list(dict.fromkeys(xs))

def concat[S: (str, bytes)](a: S, b: S) -> S:
    return a + b

print(dedupe(["b", "a", "b", "c", "a"]))
print(concat("ab", "cd"), concat(b"ab", b"cd"))

(H,) = dedupe.__type_params__
(S,) = concat.__type_params__
print(H.__name__, H.__bound__, H.__constraints__)
print(S.__name__, S.__bound__, S.__constraints__)
['b', 'a', 'c']
abcd b'abcd'
H <class 'collections.abc.Hashable'> ()
S None (<class 'str'>, <class 'bytes'>)

The equivalent old spellings are TypeVar("H", bound=Hashable) and TypeVar("S", str, bytes).

Bounds and constraints are evaluated lazily, on first access of __bound__. That means a bound can refer to a class defined later in the module, without quotes:

from typing import Any, Protocol

class SortedList[T: Comparable]:     # Comparable is defined below
    pass

class Comparable(Protocol):
    def __lt__(self, other: Any, /) -> bool: ...

(T,) = SortedList.__type_params__
print(T.__bound__)
<class '__main__.Comparable'>

With the old syntax this needed a string: TypeVar("T", bound="Comparable").

Variance is inferred

Variance answers the question: if Dog is a subtype of Animal, is Box[Dog] a subtype of Box[Animal]?

With TypeVar you had to declare the variance yourself (TypeVar("T_co", covariant=True)), and the type checker only verified that you got it right. With the new syntax the type checker infers the variance from how the class uses T:

from collections.abc import Callable

class Animal: ...
class Dog(Animal): ...

class Box[T]:                       # read and write: invariant
    def __init__(self, item: T) -> None:
        self.item = item

class Frozen[T]:                    # read only: covariant
    def __init__(self, item: T) -> None:
        self._item = item

    @property
    def item(self) -> T:
        return self._item

class Sink[T]:                      # write only: contravariant
    def __init__(self, handler: Callable[[T], None]) -> None:
        self._handler = handler

    def send(self, item: T) -> None:
        self._handler(item)

def show_box(b: Box[Animal]) -> None: ...
def show_frozen(f: Frozen[Animal]) -> None: ...
def feed_dogs(s: Sink[Dog]) -> None: ...

show_box(Box(Dog()))            # ok: inferred as Box[Animal] from context
dog_box = Box(Dog())
show_box(dog_box)               # error: Box is invariant
show_frozen(Frozen(Dog()))      # ok
dog_frozen = Frozen(Dog())
show_frozen(dog_frozen)         # ok: Frozen is covariant
animal_sink = Sink[Animal](print)
feed_dogs(animal_sink)          # ok: Sink is contravariant
dog_sink = Sink[Dog](print)
def feed_animals(s: Sink[Animal]) -> None: ...
feed_animals(dog_sink)          # error
$ mypy variance.py
variance.py:31: error: Argument 1 to "show_box" has incompatible type "Box[Dog]"; expected "Box[Animal]"  [arg-type]
variance.py:39: error: Argument 1 to "feed_animals" has incompatible type "Sink[Dog]"; expected "Sink[Animal]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

pyright tells you which variance it inferred:

$ pyright variance.py
variance.py:31:10 - error: Argument of type "Box[Dog]" cannot be assigned to parameter "b" of type "Box[Animal]" in function "show_box"
    "Box[Dog]" is not assignable to "Box[Animal]"
      Type parameter "T@Box" is invariant, but "Dog" is not the same as "Animal" (reportArgumentType)
variance.py:39:14 - error: Argument of type "Sink[Dog]" cannot be assigned to parameter "s" of type "Sink[Animal]" in function "feed_animals"
    "Sink[Dog]" is not assignable to "Sink[Animal]"
      Type parameter "T@Sink" is contravariant, but "Dog" is not a supertype of "Animal"
        "Animal" is not assignable to "Dog" (reportArgumentType)
2 errors, 0 warnings, 0 informations

The only difference between Box and Frozen is that Box.item is a writable attribute. Making it read-only (a property, a Final attribute or a frozen dataclass) is enough to make the class covariant. At runtime the type parameter only records that its variance is to be inferred: T.__infer_variance__ is True, and __covariant__ and __contravariant__ are both False.

Scoping rules

A type parameter exists only inside the function or class that declares it. It is not a module-level name:

from typing import Generic

def identity[T](x: T) -> T:
    return x

try:
    T
except NameError as e:
    print("NameError:", e)

try:
    class Bad[T](Generic[T]):
        pass
except TypeError as e:
    print("TypeError:", e)
NameError: name 'T' is not defined
TypeError: Cannot inherit from Generic[...] multiple times.

This means every function can just call its parameter T, without names like T_co, KT or _T1 to avoid clashes. Some other rules:

Type aliases with the type statement

A type alias gives a long type a short name. Python 3.12 added the type statement for them. Aliases can be generic and can refer to themselves or to names defined later:

type Point = tuple[float, float]
type Pair[T] = tuple[T, T]
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
type Tree = Node | None              # Node is defined below

class Node:
    def __init__(self, value: int, left: Tree = None, right: Tree = None) -> None:
        self.value, self.left, self.right = value, left, right

def midpoint(a: Point, b: Point) -> Point:
    return ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)

def swap[T](p: Pair[T]) -> Pair[T]:
    return (p[1], p[0])

print(midpoint((0, 0), (4, 2)))
print(swap((1, 2)))

print(type(Point))
print(Point.__name__, "=", Point.__value__)
print(Tree.__value__)
print(Pair.__type_params__)
print(Pair[int], type(Pair[int]))
print(Json.__value__)
(2.0, 1.0)
(2, 1)
<class 'typing.TypeAliasType'>
Point = tuple[float, float]
__main__.Node | None
(T,)
Pair[int] <class 'types.GenericAlias'>
dict[str, Json] | list[Json] | str | int | float | bool | None

The right-hand side is not evaluated when the type statement runs. It is evaluated the first time something reads __value__. That's why Json can refer to itself and Tree can refer to Node before Node exists. The other side of laziness is that a typo isn't reported until the value is used:

type Point = tuple[float, float]

try:
    isinstance((1.0, 2.0), Point)
except TypeError as e:
    print("TypeError:", e)

try:
    Point((1.0, 2.0))
except TypeError as e:
    print("TypeError:", e)

type Oops = UndefinedName
print("Oops defined")
try:
    Oops.__value__
except NameError as e:
    print("NameError:", e)
TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
TypeError: 'typing.TypeAliasType' object is not callable
Oops defined
NameError: name 'UndefinedName' is not defined

A type alias is a TypeAliasType object, not the type itself, so you can't call it or pass it to isinstance(). It's meant for annotations. If you need the value at runtime, use Point.__value__.

Type checkers understand recursive aliases, so Json really checks nested data:

from typing import reveal_type

type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
type Pair[T] = tuple[T, T]

def swap[T](p: Pair[T]) -> Pair[T]:
    return (p[1], p[0])

config: Json = {"name": "app", "ports": [80, 443], "debug": False}
bad: Json = {"when": {1, 2}}
reveal_type(swap((1, 2)))
$ mypy aliases.py
aliases.py:10: error: Dict entry 0 has incompatible type "str": "set[int]"; expected "str": "dict[str, Json] | list[Json] | str | int | float | None"  [dict-item]
aliases.py:11: note: Revealed type is "tuple[int, int]"
Found 1 error in 1 file (checked 1 source file)

Before 3.12, aliases were plain assignments, optionally marked with TypeAlias (3.10) so the checker knew they weren't ordinary variables. Recursive and forward references needed strings, and a generic alias needed a module-level TypeVar:

from typing import TypeAlias, TypeVar, Union

T = TypeVar("T")

Point: TypeAlias = tuple[float, float]
Pair: TypeAlias = tuple[T, T]
Json: TypeAlias = Union[dict[str, "Json"], list["Json"], str, int, float, bool, None]

To get a lazy TypeAliasType on older Pythons, the typing_extensions package provides TypeAliasType("Pair", tuple[T, T], type_params=(T,)).

Type parameter defaults (Python 3.13)

Since Python 3.13 a type parameter can have a default, written [T = SomeType]. The default is used when the user leaves the type argument out, so a bare Response means Response[str] instead of Response[Any]:

from typing import reveal_type

class Response[T = str]:
    def __init__(self, status: int, body: T) -> None:
        self.status = status
        self.body = body

class Cache[K = str, V = bytes]:
    def __init__(self) -> None:
        self._data: dict[K, V] = {}

    def put(self, key: K, value: V) -> None:
        self._data[key] = value

def handle(r: Response) -> None:          # bare Response means Response[str]
    reveal_type(r.body)

def handle_json(r: Response[dict[str, int]]) -> None:
    reveal_type(r.body)

c: Cache = Cache()
reveal_type(c)
c2: Cache[int] = Cache()
reveal_type(c2)
c.put("logo", b"\x89PNG")
c.put("logo", "not bytes")
$ mypy defaults.py
defaults.py:16: note: Revealed type is "str"
defaults.py:19: note: Revealed type is "dict[str, int]"
defaults.py:22: note: Revealed type is "defaults.Cache[str, bytes]"
defaults.py:24: note: Revealed type is "defaults.Cache[int, bytes]"
defaults.py:26: error: Argument 2 to "put" of "Cache" has incompatible type "str"; expected "bytes"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Cache[int] fills K and takes the default for V. As with function arguments, a parameter without a default can't follow one with a default: class Bad[T = int, U] is SyntaxError: non-default type parameter 'U' follows default type parameter. Defaults can be combined with a bound ([T: Animal = Dog]), and they work in type aliases too (type Result[T, E = Exception] = ...).

At runtime the default is stored in __default__:

class Cache[K = str, V = bytes]:
    pass

K, V = Cache.__type_params__
print(K, K.__default__, K.has_default())
print(V, V.__default__)

def no_default[T](x: T) -> T:
    return x

(T,) = no_default.__type_params__
print(T.has_default(), T.__default__)
K <class 'str'> True
V <class 'bytes'>
False typing.NoDefault

The old spelling is TypeVar("T", default=str). The default= argument was added to typing.TypeVar in 3.13, and typing_extensions.TypeVar provides it on older versions.

ParamSpec and TypeVarTuple

The brackets can also declare the other two kinds of type parameters. **P declares a ParamSpec (a whole parameter list, used to type decorators) and *Ts declares a TypeVarTuple (a variable number of types):

from collections.abc import Callable

def logged[**P, R](fn: Callable[P, R]) -> Callable[P, R]:
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        print(f"calling {fn.__name__}{args}")
        return fn(*args, **kwargs)
    return wrapper

@logged
def add(a: int, b: int) -> int:
    return a + b

def call_with[*Ts, R](fn: Callable[[*Ts], R], *args: *Ts) -> R:
    return fn(*args)

def repeat(s: str, n: int) -> str:
    return s * n

print(add(2, 3))
print(call_with(repeat, "ab", 3))
print([type(p).__name__ for p in logged.__type_params__ + call_with.__type_params__])
calling add(2, 3)
5
ababab
['ParamSpec', 'TypeVar', 'TypeVarTuple', 'TypeVar']

The decorated add keeps its signature, so add(1, "2") and call_with(repeat, "ab", "3") are both reported by the type checker:

$ mypy check_decorators.py
check_decorators.py:2: error: Argument 2 to "add" has incompatible type "str"; expected "int"  [arg-type]
check_decorators.py:3: error: Argument 1 to "call_with" has incompatible type "Callable[[str, int], str]"; expected "Callable[[str, str], str]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Previously you wrote P = ParamSpec("P") and Ts = TypeVarTuple("Ts") at module level. Typing decorators, including Concatenate, deserves an article of its own.

Compatibility

The bracket syntax and the type statement are new grammar. On Python 3.11 or older, the module fails to parse:

$ py -3.10 -c "def first[T](xs: list[T]) -> T: return xs[0]"
  File "<string>", line 1
    def first[T](xs: list[T]) -> T: return xs[0]
             ^
SyntaxError: invalid syntax

Defaults ([T = int]) need Python 3.13, so they are a SyntaxError on 3.12. from __future__ import ... can't help because this is syntax, not annotation evaluation. If a library has to support older versions, keep using TypeVar, Generic and TypeAlias, with typing_extensions for defaults and TypeAliasType. Both styles mean the same thing to type checkers, so you can switch a module once your minimum version is 3.12. Ruff's UP046, UP047 and UP040 rules (pyupgrade) can do the rewrite for you.

Current versions of mypy, pyright and other type checkers support both PEP 695 and PEP 696.

Summary

Feature Old spelling New spelling
generic function T = TypeVar("T"), def f(x: T) -> T def f[T](x: T) -> T (3.12)
generic class class Box(Generic[T]) class Box[T] (3.12)
bound TypeVar("T", bound=Animal) [T: Animal]
constraints TypeVar("S", str, bytes) [S: (str, bytes)]
variance TypeVar("T_co", covariant=True) inferred
type alias Point: TypeAlias = tuple[float, float] type Point = tuple[float, float] (3.12)
generic alias Pair: TypeAlias = tuple[T, T] type Pair[T] = tuple[T, T]
default TypeVar("T", default=str) [T = str] (3.13)
ParamSpec / TypeVarTuple P = ParamSpec("P"), Ts = TypeVarTuple("Ts") [**P], [*Ts]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents