3.11. Typing Alias

  • Since Python 3.12 you can use type soft-keyword to define type aliases

  • Since Python 3.12 PEP 695 - Type Parameter Syntax

3.11.1. Union

>>> def add(a: int|float, b: int|float) -> int|float:
...     return a + b

3.11.2. Type Keyword

  • Since Python 3.12 PEP 695 - Type Parameter Syntax

  • definition will stay until the end of the scope (module, class, function)

You can use type soft-keyword to define type aliases

>>> type number = int|float
>>>
>>> def add(a: number, b: number) -> number:
...     return a + b

3.11.3. Type Parameter

  • Since Python 3.12 PEP 695 - Type Parameter Syntax

  • It is only available during function definition

But, also there is a new syntax for defining type aliases available during function definition

>>> def add[number: (int,float)](a: number, b: number) -> number:
...     return a + b

3.11.4. Type Generic

  • class Array[T] - type generic

  • class Array[T: (int,float)] - type generic with constraints

>>> class List[T]:
...     data: list[T]
...
...     def __init__(self):
...        self.data: list[T] = []
...
...     def append(self, x: T):
...         self.data.append(x)
...
...     def pop(self) -> T:
...         return self.data.pop()

3.11.5. Type Generic with Constraints

  • class Array[T: (int,float)] - type generic with constraints

>>> class Array[T: (int,float)]:
...     data: list[T]
...
...     def __init__(self):
...         self.data: list[T] = []
...
...     def append(self, x: T):
...         self.data.append(x)
...
...     def pop(self) -> T:
...         return self.data.pop()

3.11.6. Use Case - 1

>>> type GeographicCoordinate = tuple[float, float]
>>>
>>> locations: list[GeographicCoordinate] = [
...     (25.91375, -60.15503),
...     (-11.01983, -166.48477),
...     (-11.01983, -166.48477),
... ]

3.11.7. Use Case - 2

Without aliases:

>>> DATA: list[tuple[str, str, str, str, str] | tuple[float, float, float, float, str]] = [
...     ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
...     (5.8, 2.7, 5.1, 1.9, 'virginica'),
...     (5.1, 3.5, 1.4, 0.2, 'setosa'),
...     (5.7, 2.8, 4.1, 1.3, 'versicolor'),
...     (6.3, 2.9, 5.6, 1.8, 'virginica'),
...     (6.4, 3.2, 4.5, 1.5, 'versicolor'),
...     (4.7, 3.2, 1.3, 0.2, 'setosa'),
... ]

With aliases:

>>> type row = tuple[float, float, float, float, str]
>>>
>>> data: list[row] = [
...     (4.7, 3.2, 1.3, 0.2, 'setosa'),
...     (7.0, 3.2, 4.7, 1.4, 'versicolor'),
...     (7.6, 3.0, 6.6, 2.1, 'virginica'),
... ]

With aliases and union:

>>> type header = tuple[str, str, str, str, str]
>>> type row = tuple[float, float, float, float, str]
>>>
>>> DATA: list[header|row] = [
...     ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
...     (5.8, 2.7, 5.1, 1.9, 'virginica'),
...     (5.1, 3.5, 1.4, 0.2, 'setosa'),
...     (5.7, 2.8, 4.1, 1.3, 'versicolor'),
...     (6.3, 2.9, 5.6, 1.8, 'virginica'),
...     (6.4, 3.2, 4.5, 1.5, 'versicolor'),
...     (4.7, 3.2, 1.3, 0.2, 'setosa'),
... ]

3.11.8. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Typing Alias TypeKeyword
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Define type `T` to annotate variables
# 2. Use `type` keyword and union syntax
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj typ `T` do anotacji zmiennych
# 2. Użyj słowa kluczowego `type` oraz notacji unii
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'

>>> from typing import get_type_hints
>>> get_type_hints(add)
{'a': T, 'b': T, 'return': T}
"""

# Define type `T` to annotate variables
# Use `type` keyword and union syntax
def add(a: int | float, b: int | float) -> int | float:
    return a + b


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Typing Alias TypeParameters
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Modify definition of a function `add`
# 2. Refactor type definition using Python 3.12 syntax,
#    example: `def run[T: int](a: T, b: T) -> T: ...`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj definicję funkcji `add`
# 2. Zrefaktoruj definiowanie typu używając składni Python 3.12,
#    przykład: `def run[T: int](a: T, b: T) -> T: ...`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'

>>> from typing import get_type_hints
>>> get_type_hints(add)
{'a': T, 'b': T, 'return': T}
"""

# Modify definition of a function `add`
# Refactor type definition using Python 3.12 syntax,
# example: `def run[T: int](a: T, b: T) -> T: ...`
def add(a: int | float, b: int | float) -> int | float:
    return a + b