Note: As others mentioned, Python type hinting (by default) doesn't have any impact on runtime behavior, and it's used in static analysis and the like.
From Python 3.10 onwards, you can use |
separator for union types. Taking the example from What's New In Python 3.10:
def square(number: int | float) -> int | float:
return number ** 2
# Instead of
def square(number: Union[int, float]) -> Union[int, float]:
return number ** 2
Also, if you are using Python 3.7+, you can have the feature by using the __future__
package, with some limitations, however:
from __future__ import annotations
# Works in Python 3.7+
def square(number: int | float) -> int | float:
return number ** 2
# Works only in Python 3.10+
isinstance(3.10, int | float)
numeric = int | float
For more information, see Union Types documentation and PEP 604.