The short answer to your question is that you should use either TypeVars or Sequence - using List[Union[int, float]]
it could potentially lead to an error in your code!
, , PEP 484 ( , Java, #...). , . , , , , un-typesafe, .
:
from typing import Union, List
Num = Union[int, float]
def quick_sort(arr: List[Num]) -> List[Num]:
arr.append(3.14)
return arr
foo = [1, 2, 3, 4]
quick_sort(foo)
typecheck, ! , foo
, List[int]
, .
, , int
Union[int, float]
, , List[int]
List[Union[int, float]]
.
.
- , Sequence
:
from typing import Union, Sequence
Num = Union[int, float]
def quick_sort(arr: Sequence[Num]) -> Sequence[Num]:
return arr
, List, , (, , Sequence API ). , .
, , ints, float, . TypeVars :
from typing import Union, List, TypeVar
Num = TypeVar('Num', int, float)
def quick_sort(arr: List[Num]) -> List[Num]:
return arr
foo = [1, 2, 3, 4]
quick_sort(foo)
bar = [1.0, 2.0, 3.0, 4.0]
quick_sort(foo)
"" , , .
- , , .