3.11. Typing Alias¶
Since Python 3.12 you can use
type
soft-keyword to define type aliasesSince Python 3.12 PEP 695 - Type Parameter Syntax
3.11.1. The old way¶
>>> def add(a: int|float, b: int|float) -> int|float:
... return a + b
3.11.2. Type Keyword¶
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. Function Type Alias¶
Since Python 3.12 PEP 695 - Type Parameter Syntax
Similar to
type
soft-keywordIt 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. Assignments¶
"""
* Assignment: Typing Annotations Alias
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min
English:
1. Declare proper types for variables
2. Use `type` soft keyword and pipe notation `|`
3. Run doctests - all must succeed
Polish:
1. Zadeklaruj odpowiedni typ zmiennych
2. Użyj słowa kluczowego `type` oraz pionowej kreski `|`
3. Uruchom doctesty - wszystkie muszą się powieść
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert data == 0.0, \
'Do not modify variable `b` value, just add type annotation'
"""
# Declare proper types for variables
# Use `type` soft keyword and pipe notation `|`
T = ...
# Do not modify lines below
data: T = 0
data: T = 0.0