Sub topic 9
Naming Complex Types with Aliases
This chapter assumes you can write basic annotations, use unions such as str | None, and annotate callables with Callable. Examples use Python 3.12 or newer unless noted.
Why alias a type
Long annotations are hard to read, and repeating them invites drift. A type alias is a name for a type expression. A checker treats the alias and the expression as the same type.
from collections.abc import Callable
Handler = Callable[[str], int]
Scores = dict[str, list[int]]
def run(handler: Handler, text: str) -> int:
return handler(text)
def best(scores: Scores) -> str:
return max(scores, key=lambda name: max(scores[name]))
print(run(len, "hello"))
print(best({"Ada": [90, 95], "Bo": [80]}))This prints 5 and then Ada. If Scores later becomes dict[str, tuple[int, ...]], you change one line.
Marking an alias explicitly
A plain assignment such as Handler = ... looks like an ordinary variable. A checker has to guess that it is an alias. You can state your intent in two ways.
from collections.abc import Callable
from typing import TypeAlias
Handler: TypeAlias = Callable[[str], int] # Python 3.10+
type Parser = Callable[[str], list[str]] # Python 3.12+Prefer the type statement on 3.12 and newer. It evaluates the right-hand side lazily, so an alias can refer to itself or to names defined later.
Recursive aliases
Nested data such as JSON needs a self-referencing alias. This works with the type statement:
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
def depth(value: Json) -> int:
if isinstance(value, dict):
return 1 + max(map(depth, value.values()), default=0)
if isinstance(value, list):
return 1 + max(map(depth, value), default=0)
return 0
print(depth({"a": [1, {"b": None}]}))This prints 3. With the older TypeAlias form, a self-reference must be a quoted string, for example "Json".
Common errors
- Expecting a distinct type.
UserId = intcreates only another name. A checker accepts anyintwhereUserIdis expected. If you need the checker to separate the two, useNewType("UserId", int). - Aliasing a value instead of a type.
Limit = 3is a constant. Only type expressions can be aliases. - Using an alias before it exists. With a plain assignment, the alias must be defined above its first runtime use. Quote it or use
typeto avoid this. - Hiding too much. Short, familiar types such as
list[int]read better inline. Alias a type when it is long, repeated, or carries meaning, such asScores.
Exercise
You write UserId = int and a function def load(user_id: UserId) -> str. A teammate calls load(42) with a plain int. Does a static checker report an error, and which tool would make it do so?
Show answer
No error. An alias is only another name for int, so any int is accepted. NewType("UserId", int) creates a distinct type, and the checker then rejects a plain int.