Name Reusable Types with Aliases
Core idea
A type alias gives a complex type expression a descriptive name. Python 3.12+ supports type Address = tuple[str, int], which creates a TypeAliasType. The alias denotes the same static type, not a new nominal type. On earlier versions an annotated assignment with typing.TypeAlias can express an explicit alias.
type Address = tuple[str, int]def describe(address: Address) -> str: host, port = address return f'{host}:{port}'print(describe(('local', 8000)))The alias communicates the tuple layout at the call boundary.
Inspect an alias
from typing import TypeAliasTypetype Scores = list[int]print(isinstance(Scores, TypeAliasType))print(Scores.__value__ == list[int])The type statement creates an alias object whose value is the type expression.
Common mistake
Do not instantiate an alias made by the type statement as though it were a class. A type alias is not a runtime validator or a distinct domain type.
Practice
Define type Row = tuple[str, int] and type Table = list[Row]. Annotate a function that sums the integer fields.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Type aliases
Check your understanding of type aliases.
What is printed?
type Pair = tuple[int, int]def total(p: Pair) -> int: return sum(p)print(total((3,4)))What is printed?
type IDs = list[int]print(IDs.__name__)Which Python version introduced the type alias statement?
Does an alias create a distinct nominal static type?