5.2. Type Annotation Primitives

5.2.1. Alias

  • Used to make types more readable

Declaration:

>>> data = int | float

Example:

>>> number = int | float
>>>
>>> age: number = 10      # ok
>>> age: number = 10.5    # ok
>>> age: number = None    # error

5.2.2. Union

  • Used to inform static type checker that the variable should either X or Y

  • Since Python 3.10: PEP 604 -- Allow writing union types as X | Y

  • int | str == str | int

Declaration:

>>> data: int | float
>>> data: int | float = 1337
>>> data: int | float = 1.337

Example:

>>> data: int | float
>>>
>>> data = 1337     # ok
>>> data = 1.337    # ok
>>> data = 'hello'  # error

Result of this expression would then be valid in isinstance() and issubclass():

>>> isinstance(1337, int|float)
True

5.2.3. Optional

  • Used to inform static type checker that the variable should be X or None

  • int | None == None | int

Declaration:

>>> data: int | None
>>> data: int | None = 1337
>>> data: int | None = None

Example:

>>> number: int | None
>>>
>>> number = 1337    # ok
>>> number = None    # ok
>>> number = 1.0     # error

Result of this expression would then be valid in isinstance() and issubclass():

>>> isinstance(1337, int|None)
True

5.2.4. Final

  • Used to inform static type checker the value should not change

  • Used to define constants

  • Since Python 3.8: PEP 591 -- Adding a final qualifier to typing

In Python there is not such thing as constants. All values can be changed during the runtime. However using Final we can achieve similar effect. Static type checker will ensure that the value should not change during the program.

SetUp:

>>> from typing import Final

Declaration:

>>> data: Final
>>> data: Final[int]
>>> data: Final[float]
>>> data: Final[bool]
>>> data: Final[str]

Definition:

>>> pressure: Final[float] = 1013.25    # ok
>>> pressure = 1024.00                  # error

5.2.5. Literal

SetUp:

>>> from typing import Literal

Declaration:

>>> data: Literal['one', 'two', 'three']

Problem:

>>> agency: str
>>>
>>> agency = 'NASA'         # ok
>>> agency = 'ESA'          # ok
>>> agency = 'Not existing' # ok

Solution:

>>> agency: Literal['NASA', 'ESA', 'POLSA']
>>>
>>> agency = 'NASA'          # ok
>>> agency = 'ESA'           # ok
>>> agency = 'Not existing'  # error

5.2.6. Use Case - 0x01

>>> firstname: str = 'Mark'
>>> lastname: str = 'Watney'
>>> age: int | float = 40
>>> adult: bool = True
>>> agency: Literal['NASA', 'ESA', 'POLSA'] = 'NASA'
>>> job: str | None = None
>>> height: int | float | None = 185
>>> weight: int | float | None = None

5.2.7. Use Case - 0x02

>>> SECOND: Final[int] = 1
>>> MINUTE: Final[int] = 60 * SECOND
>>> HOUR: Final[int] = 60 * MINUTE
>>> DAY: Final[int] = 24 * HOUR

5.2.8. Further Reading

5.2.9. References

1

Briggs, J. Type Annotations in Python. Year: 2021. Retrieved: 2022-04-08. URL: https://towardsdatascience.com/type-annotations-in-python-d90990b172dc