type alias
In Python, a type alias allows you to create an alternative name for an existing type. It’s a convenient way to make your type hints more readable.
You can create a type alias by assigning a type to a variable name. Starting with Python 3.12, you can also use the type statement (PEP 695) to explicitly declare type aliases, which is the preferred approach because it avoids ambiguity with regular variable assignments.
Type aliases are particularly useful when you have a complex type that you use frequently across your codebase. By using a type alias, you can refer to the complex type with a less complex and more descriptive name, enhancing code readability and maintainability.
Example
Here’s a quick example of how you can use a type alias in Python:
>>> Coordinate = tuple[float, float]
>>> Path = list[Coordinate]
>>> # Type hints with the type alias
>>> path: Path = [(1.0, 2.0), (2.0, 3.5), (5.0, 6.0)]
>>> # Type hints without the type alias
>>> path: list[tuple[float, float]] = [(1.0, 2.0), (2.0, 3.5), (5.0, 6.0)]
In this example, Coordinate is a type alias for a tuple containing two floating-point numbers, and Path is a type alias for a list of coordinates. This way, the code that uses type hints looks more readable and less complex.
In Python 3.12+, you can use the type statement for the same purpose:
>>> type Coordinate = tuple[float, float]
>>> type Path = list[Coordinate]
Related Resources
Tutorial
Python Type Checking (Guide)
In this guide, you'll look at Python type checking. Traditionally, types have been handled by the Python interpreter in a flexible but implicit way. Recent versions of Python allow you to specify explicit type hints that can be used by different tools to help you develop your code more efficiently.
For additional information on related topics, take a look at the following resources:
- Python Protocols: Leveraging Structural Subtyping (Tutorial)
- Duck Typing in Python: Writing Flexible and Decoupled Code (Tutorial)
- Python Type Checking (Course)
- Python Type Checking (Quiz)
- Exploring Protocols in Python (Course)
- Python Protocols: Leveraging Structural Subtyping (Quiz)
- Getting to Know Duck Typing in Python (Course)
- Duck Typing in Python: Writing Flexible and Decoupled Code (Quiz)