Python Type Alias Statements
Learn Python's type statement for creating type aliases, using aliases in annotations, and understanding their lazy evaluation without confusing them with the type() function.
Intermediate
Python can give a descriptive name to a type expression with the
type statement. A type alias is a named description of an existing type expression; it does not create a new runtime class.
Create a type alias
The basic form is
type Point = tuple[float, float]. The name on the left becomes the alias, and the expression on the right describes the aliased type.
|
|
The alias gives a reusable name to the type expression.
Use an alias in an annotation
A type alias can be used anywhere an annotation expression can be used. This keeps function signatures shorter and gives related values a shared vocabulary.
|
|
The alias is used as the annotation for a function parameter; the function still behaves like ordinary Python code.
An alias can name a larger type expression
The right-hand side can be a type expression built from other types. Aliases are especially useful when the same long expression would otherwise be repeated.
|
|
Aliases can be composed to make a larger annotation easier to read.
The alias is a TypeAliasType object
Executing a
type statement creates a type-alias object. Its value can be inspected through the alias object's metadata, including its name and underlying type expression.
|
|
The alias has its own name and exposes the aliased type expression through __value__.
Type aliases are evaluated lazily
The value of a type alias is evaluated lazily in its annotation scope. This means the referenced type expression does not have to be evaluated at the moment the alias statement runs.
|
|
The later binding can exist before the alias value is requested because the alias value is evaluated lazily.
Type aliases do not enforce runtime types
A type alias is not a runtime validation rule. Using an alias in an annotation does not make Python automatically reject values of another type; annotations remain descriptive metadata unless some other tool or explicit code performs checking.
|
|
The annotation uses the alias, but the interpreter does not automatically enforce it at the call site.
Do not confuse type with type()
The word
type in a type-alias statement is a soft keyword. It does not replace the built-in
type() function, which still asks about an object's runtime type.
|
|
type(value) inspects a runtime object; the type statement creates a named type alias.
Key idea
The
type statement gives an existing type expression a reusable name. It creates a type-alias object, evaluates the alias value lazily, and improves the readability of annotations without creating a new runtime class or enforcing types by itself.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.