Sub topic 9
Naming complex types with aliases
This chapter assumes you can annotate parameters and return values, and that you know X | None, built-in generics such as dict[str, list[int]], and Callable. It also assumes Python 3.10 or newer. Where a feature needs 3.12, the text says so.
Why aliases exist
Annotations get long. A function that takes a mapping of names to score lists and a callback quickly looks like this:
from collections.abc import Callable
def report(
scores: dict[str, list[int]],
on_error: Callable[[str, Exception], None] | None = None,
) -> dict[str, list[int]] | None:
return scores or NoneA type alias is a name for a type expression. It shortens the signature, and it gives a concept one name that you define in one place and reuse everywhere.
The basic alias
At module level, assign a type expression to a name. Use a capitalized name, as you would for a class.
from collections.abc import Callable
Scores = dict[str, list[int]]
ErrorHandler = Callable[[str, Exception], None]
def report(scores: Scores, on_error: ErrorHandler | None = None) -> Scores | None:
return scores or None
print(report({"ada": [3, 9]}))A checker reads Scores as exactly dict[str, list[int]]. Aliases can be combined: ErrorHandler | None is a union built from an alias.
Explicit aliases with TypeAlias
A bare assignment like Scores = dict[str, list[int]] is ambiguous to a reader and sometimes to a checker. The same line could be an ordinary variable that holds a class object. Annotating it with TypeAlias (Python 3.10+) removes the doubt:
from typing import TypeAlias
UserId: TypeAlias = int
Scores: TypeAlias = dict[str, list[int]]
def best(scores: Scores) -> dict[str, int]:
return {name: max(vals) for name, vals in scores.items() if vals}
print(best({"ada": [3, 9], "bob": []}))This prints {'ada': 9}. Use TypeAlias when the right-hand side is not obviously a type. It is required when the right side is a quoted string, as in the forward-reference case below.
An alias is not a new type
This is the most common misunderstanding. UserId above is another name for int, not a separate type. A checker accepts any int where a UserId is expected, and the reverse.
from typing import TypeAlias
UserId: TypeAlias = int
OrderId: TypeAlias = int
def cancel(order: OrderId) -> None:
print(f"cancelling {order}")
user: UserId = 7
cancel(user) # accepted: both names mean intIf you need the checker to keep the two apart, use typing.NewType, which creates a distinct type that is still an int at runtime:
from typing import NewType
UserId = NewType("UserId", int)
OrderId = NewType("OrderId", int)
def cancel(order: OrderId) -> None:
print(f"cancelling {order}")
cancel(OrderId(5)) # fine
cancel(UserId(7)) # a checker reports an incompatible argument typeThe last call still runs. Hints are not enforced at runtime, and only the checker complains.
Aliases for unions and callables
Aliases earn their keep with unions and Callable, where the expression is hardest to read.
from collections.abc import Callable
from typing import TypeAlias
Number: TypeAlias = int | float
Transform: TypeAlias = Callable[[Number], Number]
def apply_all(value: Number, steps: list[Transform]) -> Number:
for step in steps:
value = step(value)
return value
print(apply_all(2, [lambda n: n * 3, lambda n: n + 0.5]))This prints 6.5. If you later widen Number to include Decimal, one line changes and every signature follows.
Generic aliases
An alias can contain a type variable. Subscripting the alias then fills in the variable.
from typing import TypeAlias, TypeVar
T = TypeVar("T")
Pair: TypeAlias = tuple[T, T]
def swap(pair: Pair[int]) -> Pair[int]:
first, second = pair
return second, first
print(swap((1, 2)))Pair[int] means tuple[int, int]. If you use a generic alias without subscripting it, checkers treat the missing argument as Any, which silently loosens checking. Write Pair[int], not bare Pair.
The type statement in Python 3.12
Python 3.12 added a dedicated syntax. It declares an alias without importing TypeAlias and without a separate TypeVar:
type Scores = dict[str, list[int]]
type Pair[T] = tuple[T, T]
def swap(pair: Pair[int]) -> Pair[int]:
return pair[1], pair[0]
print(swap((1, 2)))The right-hand side is evaluated lazily, only when something asks for it. This allows an alias to refer to itself or to names defined later in the file.
| Form | Minimum Python | Lazy evaluation | Notes | Column |
|---|---|---|---|---|
| `Name = int \ | str` | 3.10 | No | Ambiguous with a variable |
| `Name: TypeAlias = int \ | str` | 3.10 | No | Explicit; works with quoted strings |
| `type Name = int \ | str` | 3.12 | Yes | Supports `type Name[T] = ...` |
An alias made with type is an object of class TypeAliasType, not the underlying type. You cannot subclass it, and you cannot call it to construct a value.
Recursive aliases
A recursive alias refers to itself, such as JSON data. With type this is direct:
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
def count_leaves(node: Json) -> int:
if isinstance(node, dict):
return sum(count_leaves(v) for v in node.values())
if isinstance(node, list):
return sum(count_leaves(v) for v in node)
return 1
print(count_leaves({"a": [1, 2], "b": {"c": None}}))This prints 3. Before 3.12, quote the entire right-hand side so Python does not evaluate the name before it exists:
from typing import TypeAlias
Json: TypeAlias = "dict[str, Json] | list[Json] | str | int | float | bool | None"Quote the whole expression. Writing dict[str, "Json"] | None fails at runtime, because | between a dict[...] and None is fine but a bare string cannot be combined with |.
Common errors
- Using an alias with
isinstance.isinstance(x, Scores)raisesTypeErrorfor subscripted generics. Check against the plain class,dict, instead. Unions such asint | floatdo work withisinstanceon 3.10+, but an alias created withtypedoes not. - Defining an alias inside a function or branch. Checkers expect aliases at module or class level. A name that is reassigned, or defined under an
if, may be treated as a variable, and you will see errors such as "variable not allowed in type expression". - Using lowercase or reusing names.
scores = dict[str, int]looks like a variable. Capitalize aliases and give each a single definition. - Expecting runtime enforcement. An alias changes nothing about runtime behavior. Calling
best("not a dict")still runs until something fails. - Leaving out type arguments. A bare
Pairis read asPair[Any]. Strict modes in mypy and pyright can flag this.
When to add an alias
Add one when a type appears three or more times, when the expression is hard to read, or when the name carries meaning, such as Scores. Skip it when the alias name is no clearer than the type, as in IntList = list[int]. A reader then has to look up the definition for no gain.
Exercise
A teammate writes UserId = int and OrderId = int, then is surprised that a checker accepts cancel_order(user_id). Explain why, and show how to make the checker reject it.
Show answer
An alias is only another name for the same type, so UserId and OrderId are both just int to the checker. Declare distinct types with NewType: UserId = NewType("UserId", int) and OrderId = NewType("OrderId", int). Values are then created with OrderId(5), and passing a UserId where an OrderId is expected is reported by the checker. The code still runs, because hints are not enforced at runtime.
Exercise
Write an alias Matrix for a list of rows of floats, and a function total(m: Matrix) -> float that sums every entry. Use TypeAlias so it works on Python 3.10.
Show answer
from typing import TypeAlias Matrix: TypeAlias = list[list[float]] def total(m: Matrix) -> float: return sum(sum(row) for row in m) print(total([[1.0, 2.0], [3.5]])) # 6.5