Union types are used to inform the type checker:
“This variable/parameter can be any one of several different types at the same time.”
- Before Python 3.10: typing.Union
from typing import Union
def print_id(uid: Union[int, str]) -> None:
print(uid)
# Valid calls
print_id(123) # int
print_id("abc") # str
Union[int, str] indicates “either int or str is acceptable.”
- From Python 3.10 onwards: using the | operator (PEP 604)
def print_id(uid: int | str) -> None:
print(uid)
The functionality is completely equivalent, but shorter and more readable.