Sub topic 8
Generic type aliases with the type statement
This chapter assumes you can write generic functions and classes with def f[T] and class C[T], and that you know what a type checker such as mypy or pyright reports. It covers the type statement from Python 3.12. The statement gives a name to a type expression, can take its own type parameters, and is evaluated lazily.
Why aliases need type parameters
A type alias is a short name for a longer type. Aliases make signatures readable:
type Point = tuple[float, float]
def distance(a: Point, b: Point) -> float:
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5Point always means the same thing. Many useful shapes depend on an element type, though. "A pair of the same type", "a dict from str to something", and "a callback that handles some event" all have a hole that callers fill in. A generic alias adds type parameters to the alias, so the hole can be filled at each use site.
The type statement
The type statement declares type parameters in square brackets after the alias name, the same place a function or class declares them:
type Pair[T] = tuple[T, T]
type StrMap[V] = dict[str, V]
def swap[T](p: Pair[T]) -> Pair[T]:
return (p[1], p[0])
scores: StrMap[int] = {"ana": 3, "bo": 5}
flipped = swap((1, 2)) # checker infers Pair[int], that is tuple[int, int]Subscripting an alias substitutes the argument for the parameter. Pair[int] means tuple[int, int], and StrMap[int] means dict[str, int]. An alias can have several parameters, and the checker substitutes them by position:
from collections.abc import Callable
type Handler[E] = Callable[[E], None]
type Mapping2[K, V] = dict[K, list[V]]
def register[E](event_type: type[E], handler: Handler[E]) -> None:
...An alias can use the other kinds of type parameters too. A ParamSpec parameter is written **P, and a TypeVarTuple parameter is written *Ts:
from collections.abc import Callable
type Decorator[**P, R] = Callable[[Callable[P, R]], Callable[P, R]]
type Row[*Ts] = tuple[int, *Ts]Bounds, constraints and defaults on alias parameters
The parameters of an alias accept the same features as those of functions and classes. These are bounds, constraints and (from Python 3.13) defaults.
from collections.abc import Sized
type SizedPair[T: Sized] = tuple[T, T]
type Number[T: (int, float)] = list[T]
type Result[T, E = Exception] = tuple[T, None] | tuple[None, E]SizedPair[int] is reported as an error because int has no __len__. Result[str] means Result[str, Exception].
Aliases have no variance. Variance describes how a class's parameter relates subtypes, so it only applies to classes and protocols. An alias is a name that stands for another type, and the checker expands it before it compares anything.
Comparing the three alias styles
Before 3.12, aliases were plain assignments, optionally marked with TypeAlias (Python 3.10). Code that targets older versions still uses them.
from typing import TypeAlias, TypeVar
T = TypeVar("T")
Pair: TypeAlias = tuple[T, T] # explicit alias, implicitly generic
Implicit = tuple[T, T] # implicit alias, the checker must guess| Style | Syntax | Generic | Lazy evaluation | Runtime object |
|---|---|---|---|---|
| Implicit alias | `Pair = tuple[T, T]` | Through a module-level `TypeVar` | No | The type expression itself |
| `TypeAlias` | `Pair: TypeAlias = tuple[T, T]` | Through a module-level `TypeVar` | No, unless you quote the right-hand side | The type expression itself |
| `type` statement | `type Pair[T] = tuple[T, T]` | Parameters declared on the alias | Yes | A `typing.TypeAliasType` |
The old styles have two drawbacks. The alias gets its generic parameters from whatever TypeVar objects appear on the right-hand side, so the parameter list is implicit and the order is the order of first appearance. The TypeVar objects also live at module level and are shared with every other generic definition in the file. The type statement lists the parameters explicitly and keeps them private to the alias.
Lazy evaluation and recursive aliases
The right-hand side of a type statement is not evaluated when the statement runs. It is evaluated the first time something asks for the alias's __value__. This makes a recursive alias possible, because the alias name can appear in its own definition:
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
type Tree[T] = T | list[Tree[T]]
def depth(node: Json) -> int:
if isinstance(node, dict):
return 1 + max((depth(v) for v in node.values()), default=0)
if isinstance(node, list):
return 1 + max((depth(v) for v in node), default=0)
return 0
print(depth({"a": [1, {"b": None}]})) # 3With an old-style alias, the same definition fails when the module is imported, because Json does not exist yet when the right-hand side runs:
try:
Json = dict[str, Json] | list[Json] | str | int | None
except NameError as exc:
print("NameError:", exc)Before 3.12, you would quote the inner references as "Json" and hope the checker handled the cycle. With the type statement, no quoting is needed. Forward references to names defined later in the module also work in the same way.
Laziness has one consequence you should know about. A mistake on the right-hand side, such as a misspelled name, is not reported when the module is imported. It surfaces only when the checker analyses the alias or when something reads __value__. Type checkers report it statically, so run one.
flowchart TD
A[type Pair of T equals tuple of T and T] --> B[Statement runs: TypeAliasType object is created]
B --> C[Right-hand side is stored but not evaluated]
C --> D{Something reads __value__?}
D -->|No| E[Nothing else happens at runtime]
D -->|Yes| F[Right-hand side is evaluated once and cached]
F --> G[Names such as Pair itself can now be resolved]The diagram above uses a plain flowchart, so here it is in the required form:
What an alias is at runtime
A type statement creates an instance of typing.TypeAliasType. You can inspect it:
type Pair[T] = tuple[T, T]
print(type(Pair)) # <class 'typing.TypeAliasType'>
print(Pair.__name__) # Pair
print(Pair.__type_params__) # (T,)
print(Pair.__value__) # tuple[T, T]
try:
isinstance((1, 2), Pair)
except TypeError as exc:
print("TypeError:", exc)The alias is not a class, so a few things that work with classes do not work with it:
isinstance(x, Pair)raisesTypeError. If you need a runtime check, useisinstance(x, tuple)and check the contents yourself, or readPair.__value__and inspect it.- You cannot subclass an alias.
class P(Pair[int])is an error, because an alias names a type and is not itself a type to inherit from. - You cannot call an alias to make a value.
Pair[int](1, 2)fails at runtime. Build the tuple directly. - Aliases defined with
typeare not interchangeable with their old-style counterparts at runtime. Code that testsPair is tupleor comparesPair == tuple[int, int]behaves differently.
Scope of the type parameters
The parameters of an alias belong to a scope that exists only for that alias. T in type Pair[T] = tuple[T, T] does not create a module-level name T:
type Pair[T] = tuple[T, T]
try:
print(T)
except NameError as exc:
print("NameError:", exc)This means two aliases can both use T without sharing a variable, and neither one collides with a legacy T = TypeVar("T") in the same file. Inside the scope, a type parameter shadows any outer name that is also called T.
Common errors
- Forgetting to fill in the parameters. Writing
x: Pairwithout a type argument meansPair[Any]in most checkers. Strict modes of mypy and pyright report this as a missing type argument. WritePair[int]. - Wrong number of arguments.
StrMap[int, str]is an error, because the alias has one parameter. - A parameter that is unused.
type Bad[T] = list[int]is accepted at runtime. A checker may warn thatTis unused, andBad[str]meanslist[int], which is almost certainly not what you intended. - Mixing old and new parameters. Do not use a module-level
TypeVaron the right-hand side of atypestatement that declares its own parameters. The old variable is not bound by the alias, and checkers reject this. - Targeting Python older than 3.12. The
typestatement is a syntax error on 3.11 and earlier. UseTypeAliaswithTypeVarthere. Thetyping_extensionspackage supplies aTypeAliasTypeyou can call directly,TypeAliasType("Pair", tuple[T, T], type_params=(T,)), but the statement form is not available.
Choosing a style
Use the type statement when your minimum supported version is 3.12. It makes the parameters explicit, supports recursion without quotes, and keeps type variables out of module scope. Keep TypeAlias plus TypeVar while you must support 3.11 or earlier. Do not mix the two styles in the same alias.
Exercise
Write a generic alias Callback for a function that takes one argument of type E and returns None. Then write a function notify that takes a Callback[int] and calls it with the value 42. What does Callback[str] expand to?
Show answer
type Callback[E] = Callable[[E], None] (with from collections.abc import Callable). def notify(cb: Callback[int]) -> None: cb(42). Callback[str] expands to Callable[[str], None].
Exercise
This code fails on import with a NameError. Fix it so that it works on Python 3.12 and later, and say why your fix works. from typing import TypeAlias Nested: TypeAlias = int | list[Nested]
Show answer
Replace it with type Nested = int | list[Nested]. The type statement does not evaluate its right-hand side when it runs, so the name Nested is not looked up until the value is needed. By then the alias exists, so the self-reference resolves.
Exercise
Why does isinstance(value, Pair) raise TypeError when Pair is defined with type Pair[T] = tuple[T, T], and what can you do instead?
Show answer
Pair is a typing.TypeAliasType object, not a class, so isinstance rejects it as its second argument. Check against the concrete class, for example isinstance(value, tuple) and len(value) == 2, and check the element types yourself if you need them.