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 3.12 Preview: Static Typing Improvements
In this tutorial, you'll preview the new static typing features in Python 3.12. You'll learn about the new syntax for type variables, making generics simpler to define. You'll also see how @override lets you model inheritance and how you use typed dictionaries to annotate variable keyword arguments.
For additional information on related topics, take a look at the following resources:
- How to Use Type Hints for Multiple Return Types in Python (Tutorial)
- Python 3.12: Cool New Features for You to Try (Tutorial)
- Python Type Checking (Guide) (Tutorial)
- Python Protocols: Leveraging Structural Subtyping (Tutorial)
- Duck Typing in Python: Writing Flexible and Decoupled Code (Tutorial)
- Python 3.12 Preview: Static Typing Improvements (Quiz)
- Using Type Hints for Multiple Return Types in Python (Course)
- How to Use Type Hints for Multiple Return Types in Python (Quiz)
- What's New in Python 3.12 (Course)
- 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)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.