Sub topic 8
Generic type aliases with the type statement
This chapter assumes you can write generic functions and classes with the Python 3.12 [T] syntax, and that you run a static checker such as mypy or pyright. It covers how to name a type, including a generic or recursive one, with the type statement.
Why aliases need their own syntax
A type alias is a name for a type expression. Long unions and nested generics read better with a name, and a generic alias lets you reuse a shape with different type arguments.
Before 3.12 you wrote an alias as a plain assignment, such as Pair = tuple[int, int]. That is an ordinary variable assignment. A checker has to guess that you meant an alias, and the assignment runs immediately, so it cannot refer to a name that is not defined yet.
The type statement
The type statement, added in Python 3.12, declares an alias explicitly. Type parameters go in square brackets after the name, the same way they do for functions and classes.
type Pair[T] = tuple[T, T]
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
def swap[T](p: Pair[T]) -> Pair[T]:
return (p[1], p[0])
print(swap((1, 2))) # (2, 1)Pair[T] is a generic alias. Pair[int] means tuple[int, int], and the checker substitutes the argument for T wherever the alias appears. In swap, the T in [T] is bound to the argument and the result, so swap(("a", "b")) is inferred as tuple[str, str].
Json has no parameters. It refers to itself, which describes JSON data nested to any depth.
Lazy evaluation allows recursion
The right-hand side of a type statement is not evaluated when the statement runs. Python evaluates it only when you read the alias's __value__ attribute. That is why Json can mention Json inside its own definition.
The old assignment form fails for the same case:
# Json = dict[str, Json] | list[Json] | str # NameError: Json is not defined yetThe same laziness lets you refer to classes defined later in the file without quoting them as strings.
What the alias object is
A type statement creates a TypeAliasType object. It is not the type itself.
type Pair[T] = tuple[T, T]
print(type(Pair)) # <class 'typing.TypeAliasType'>
print(Pair.__name__) # Pair
print(Pair.__value__) # tuple[T, T]
print(Pair[int]) # Pair[int]Because it is a TypeAliasType and not the underlying class, you cannot call it or use it with isinstance. isinstance(x, Pair) raises TypeError. Use it only in annotations.
Choosing between the old and new forms
| Form | Example | Generic | Recursive | Explicit alias |
|---|---|---|---|---|
| Assignment | `IntPair = tuple[int, int]` | Only via a module-level `TypeVar` | Only with string quotes | No |
| `TypeAlias` annotation | `IntPair: TypeAlias = tuple[int, int]` | Same as above | Same as above | Yes |
| `type` statement | `type IntPair = tuple[int, int]` | Yes, with `[T]` | Yes | Yes |
On Python 3.11 or earlier, use the assignment or TypeAlias forms. On 3.12 or later, prefer type.
Common errors
- Reusing a name. Each
typestatement binds a name. Writingtype Pair[T] = ...twice in one scope replaces the first alias. - Forgetting the parameter on use.
Pairalone meansPair[Any]to most checkers. WritePair[int]when you mean it. - Expecting runtime checks. The alias carries no validation. It only tells the checker what to expect.
Exercise
Write a generic alias Handler[T] for a function that takes one argument of type T and returns None, then use it to annotate a function run that accepts a Handler[str] and calls it with "hi". Why would the old assignment form fail if Handler referred to itself?
Show answer
type Handler[T] = Callable[[T], None] (with from collections.abc import Callable), and def run(h: Handler[str]) -> None: h("hi"). The assignment form evaluates its right-hand side immediately, so a self-reference raises NameError because the name is not bound yet. The type statement defers evaluation, so recursion works.