I have a function with one parameter, which should take an int
or a None
as argument. There are several ways to create a type alias for such a compound type:
# test.py
import typing
IntOrNone_1 = typing.TypeVar('IntOrNone_1', int, None)
IntOrNone_2 = typing.Union[int, None]
def my_func1(xyz: IntOrNone_1):
return xyz
def my_func2(xyz: IntOrNone_2):
return xyz
my_func1(12)
my_func1(None)
my_func1(13.7)
my_func1('str')
my_func2(12)
my_func2(None)
my_func2(13.7)
my_func2('str')
Both methods do what I expect them to do, however, the correspondig mypy
erros differ slightly, but basically have the same meaning.
test.py:14: error: Value of type variable "IntOrNone_1" of "my_func1" cannot be "float"
test.py:15: error: Value of type variable "IntOrNone_1" of "my_func1" cannot be "str"
test.py:19: error: Argument 1 to "my_func2" has incompatible type "float"; expected "Optional[int]"
test.py:20: error: Argument 1 to "my_func2" has incompatible type "str"; expected "Optional[int]"
I tend to use the second approach, since it additionally reports which argument caused the error.
Are both methods indeed equivalent, as I suppose, or is one of them to be preferred?