3.3. Typing Advanced

3.3.1. 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

  • Could be with more than two types

>>> a: int | float = 1     # ok
>>> b: int | float = 1.0   # ok
>>> c: int | float | complex = 1.0   # ok

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

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

3.3.2. Optional

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

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

  • int | None == None | int

  • Could be with more than two types

>>> a: int | None = 1     # ok
>>> b: int | None = None  # ok
>>> c: int | float | None = 1.0   # ok

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

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

3.3.3. 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.

>>> from typing import Final
>>>
>>> a: Final = 1
>>> b: Final[int] = 1

3.3.4. Literal

Problem:

>>> group: str
>>>
>>> group = 'users'  # ok
>>> group = 'user'   # ok

Solution:

>>> from typing import Literal
>>>
>>> group: Literal['users', 'staff', 'admins']
>>>
>>> group = 'users'  # ok
>>> group = 'user'   # error

3.3.5. Any

>>> from typing import Any
>>>
>>> a: Any = 1           # ok
>>> b: Any = 2.0         # ok
>>> c: Any = True        # ok
>>> d: Any = None        # ok
>>> e: Any = 'Mark'      # ok

3.3.6. Use Case - 1

>>> firstname: str = 'Mark'
>>> lastname: str = 'Watney'
>>> age: int | float = 42
>>> adult: bool = True
>>> height: int | float | None = 178.0
>>> weight: int | float | None = None
>>> role: str | None = None
>>> group: Literal['users', 'staff', 'admin'] = 'users'

3.3.7. Use Case - 2

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

3.3.8. Further Reading

3.3.9. References

3.3.10. 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 Annotations Union
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Declare type for `data` variable
# 2. Type must match values defined below
# 3. Use union syntax
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zadeklaruj typ dla zmiennej `data`
# 2. Typ musi pasować do wartości zdefiniowanych poniżej
# 3. Użyj notacji unii
# 4. Uruchom doctesty - wszystkie muszą się powieść

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

>>> import importlib
>>> from typing import get_type_hints
>>> module = importlib.import_module(__name__)
>>> annotations = get_type_hints(module)

>>> assert annotations['data'] == int | float
>>> assert data == 0.0, \
'Do not modify variable `data` value, just add type annotation'
"""

# Declare type for `data` variable
# Type must match values defined below
# Use union sytnax
data: ...

# Do not modify lines below
data = 0
data = 0.0


# %% 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 Annotations Optional
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Declare type for `data` variable
# 2. Type must match values defined below
# 3. Use union syntax
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zadeklaruj typ dla zmiennej `data`
# 2. Typ musi pasować do wartości zdefiniowanych poniżej
# 3. Użyj notacji unii
# 4. Uruchom doctesty - wszystkie muszą się powieść

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

>>> import importlib
>>> from typing import get_type_hints
>>> module = importlib.import_module(__name__)
>>> annotations = get_type_hints(module)

>>> assert annotations['data'] == int | None
>>> assert data is None, \
'Do not modify variable `data` value, just add type annotation'
"""

# Declare type for `data` variable
# Type must match values defined below
# Use union sytnax
data: ...

# Do not modify lines below
data = 1
data = None


# %% 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 Annotations Any
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Declare type for `data` variable
# 2. Type must match values defined below
# 3. Use `Any` type
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zadeklaruj typ dla zmiennej `data`
# 2. Typ musi pasować do wartości zdefiniowanych poniżej
# 3. Użyj typu `Any`
# 4. Uruchom doctesty - wszystkie muszą się powieść

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

>>> import importlib
>>> from typing import get_type_hints
>>> module = importlib.import_module(__name__)
>>> annotations = get_type_hints(module)

>>> assert annotations['data'] == Any
"""
from typing import Any


# Declare type for `data` variable
# Type must match values defined below
# Use `Any` type
data: ...

# Do not modify lines below
data = 1
data = 1.0
data = 'one'


# %% 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 Annotations Literal
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Declare type for `data` variable
# 2. Type must match values defined below
# 3. Use `Literal` type
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zadeklaruj typ dla zmiennej `data`
# 2. Typ musi pasować do wartości zdefiniowanych poniżej
# 3. Użyj typu `Literal`
# 4. Uruchom doctesty - wszystkie muszą się powieść

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

>>> import importlib
>>> from typing import get_type_hints
>>> module = importlib.import_module(__name__)
>>> annotations = get_type_hints(module)

>>> assert annotations['data'] == Literal['users', 'staff', 'admins']
"""

from typing import Literal


# Declare type for `data` variable
# Type must match values defined below
# Use `Literal` type
data: ...

# Do not modify lines below
data = 'users'
data = 'staff'
data = 'admins'


# %% 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 Annotations Final
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Declare type for `data` variable
# 2. Type must match values defined below
# 3. Use `Final` type with proper subtype
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zadeklaruj typ dla zmiennej `data`
# 2. Typ musi pasować do wartości zdefiniowanych poniżej
# 3. Użyj typu `Final` z odpowiednim subtypem
# 4. Uruchom doctesty - wszystkie muszą się powieść

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

>>> import importlib
>>> from typing import get_type_hints
>>> module = importlib.import_module(__name__)
>>> annotations = get_type_hints(module)

>>> assert annotations['data'] == Final[int]
"""
from typing import Final


# Declare type for `data` variable
# Use `Final` type with proper subtype
data: ...

# Do not modify lines below
data = 1