I want to add, as a consequence of what @Carcigenicate explained:
With Union
, the operation you use between arguments has to be supported by all arguments in any permutation order:
from typing import Union
U = Union[int, str]
def add(a: U, b: U):
return a + b
Here int + int
and str + str
is OK but not the int + str
and str + int
.
Mypy says:
main.py:6: error: Unsupported operand types for + ("int" and "str")
main.py:6: error: Unsupported operand types for + ("str" and "int")
If we change +
to *
: int * str
and str * int
and int * int
is OK but Mypy doesn't like str * str
:
from typing import Union
U = Union[int, str]
def add(a: U, b: U):
return a * b
Mypy says:
main.py:6: error: Unsupported operand types for * ("str" and "str")
If we change U = Union[int, str]
to U = Union[int, float]
with above tests, it accepts. All four cases are acceptable.
Here we use TypeVar
instead to get rid of those complains, the T
is the same, either int + int
or str + str
:
from typing import TypeVar
T = TypeVar("T", int, str)
def add(a: T, b: T) -> T:
return a + b