Variables vs. Type Aliases in Python

In Python, variables can have type annotations to indicate the type of value they are expected to hold. This is particularly useful for static type checkers and for improving code readability. When defining a variable with a type annotation, you explicitly specify the type:

from typing import Type

class A:

tp: Type[A] = A

In this example:

  • tp is a variable with a type annotation.
  • Type[A] indicates that tp should hold a type object corresponding to class A.

Type Aliases

A type alias is a way to give a new name to an existing type. This can make your code more readable, especially when dealing with complex types. Type aliases are defined without an explicit type annotation at the top level of a module:

class A:

Alias = A


  • Alias is a type alias for class A.
  • This does not create a new type but simply provides an alternative name for A.

Using type aliases can simplify type annotations and make your code more descriptive.

Explicit Type Aliases with TypeAlias (PEP 613)

PEP 613 introduced the TypeAlias feature to explicitly define type aliases. This can be especially useful in larger projects or when defining type aliases in class bodies or functions. To use TypeAlias, import it from the typing module (or typing_extensions for Python 3.9 and earlier):

from typing import TypeAlias  # "from typing_extensions" in Python 3.9 and earlier

class A:

Alias: TypeAlias = A

Using TypeAlias makes it clear that Alias is intended to be a type alias, not a variable. This explicitness enhances code readability and maintainability.