Python type hints: specifying a type that should be a list of numbers (ints and / or floats)?

How can I define a function that can accept a list of numbers that can be int or float?

I tried to create a new type using Union:

num = Union[int, float]

def quick_sort(arr: List[num]) -> List[num]:
    ...

However, mypy did not like this:

 quickSortLomutoFirst.py:32: error: Argument 1 to "quickSortOuter" has
 incompatible type List[int]; expected List[Union[int, float]]  

Is there a type that includes ints and floats?

+6
source share
2 answers

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)  # We deliberately append a float
    return arr

foo = [1, 2, 3, 4]  # type: List[int]

quick_sort(foo)

# Danger!!!
# Previously, `foo` was of type List[int], but now
# it contains a float!? 

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]  # type: List[int]
quick_sort(foo)

bar = [1.0, 2.0, 3.0, 4.0]  # type: List[float]
quick_sort(foo)

"" , , .

- , , .

+7

PEP 484, :

, , , numbers.Float .., PEP , : float, int ...

Union s. Sequence[float].

: , .

+4

Source: https://habr.com/ru/post/1017239/


All Articles