Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Statements and Keywords

The type statement

Reference for the Python 3.12 type statement: declare type aliases, generic aliases with type parameters, lazy evaluation and how it differs from TypeAlias.

The type statement, added in Python 3.12, declares a type alias: a name for a type expression that you want to reuse in annotations. It creates a TypeAliasType object, and its right-hand side is evaluated lazily, so an alias can refer to names defined later and can even refer to itself for recursive types.

Do not confuse it with the built-in type() function, which returns an object's class. The statement form only appears at the start of a line as type Name = ....

Python
type UserId = int
type Pair[T] = tuple[T, T]

Try it

Python Simple and generic aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Lazy evaluation and recursive aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
type Name = type_expression
type Name[T] = type_expression
type Name[T: Bound, *Ts, **P] = type_expression
Part Description
Name The alias name, bound in the current scope.
[T, ...] Optional type parameters: plain T, bounded T: int, constrained T: (int, str), *Ts for variadic and **P for parameter specs.
type_expression Any valid annotation, including unions with |, generics and forward references.

Result: a typing.TypeAliasType object with attributes __name__, __value__ (evaluated on first access) and __type_params__.

Usage notes

  • Requires Python 3.12 or newer. On older versions use typing.TypeAlias (3.10+) or a plain assignment.
  • Lazy. The value is computed on first access of __value__, so errors in the right-hand side appear late, and forward and recursive references need no quotes.
  • Only for static typing. Aliases do nothing at run time. Python does not check annotations; tools such as mypy and pyright do.
  • Not usable with isinstance(). Test against a real class, or typing.get_args() for the pieces.
  • Aliases are distinct from NewType. An alias is interchangeable with its target, while NewType creates a type that checkers treat as separate.
  • Subscripting works for generic aliases: Pair[int] produces a generic alias object.
  • Soft keyword. type can still be used as an ordinary name (type(x), a variable called type) in other positions.
  • Scope. Type parameters live in their own annotation scope and do not leak into the surrounding code.