将类型指定为数字列表(整数 and/or 浮点数)?

Specifying a type to be a List of numbers (ints and/or floats)?

我如何指定一个函数可以接受可以是整数或浮点数的数字列表?

我试过像这样使用 Union 创建一个新类型:

num = Union[int, float]

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

然而,mypy 不喜欢这样:

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

是否有包含整数和浮点数的类型?

来自PEP 484,建议类型提示:

Rather than requiring that users write import numbers and then use numbers.Float etc., this PEP proposes a straightforward shortcut that is almost as effective: when an argument is annotated as having type float, an argument of type int is acceptable...

不要理会 Union。只要坚持 Sequence[float].

编辑:感谢 Michael 发现了 ListSequence 之间的区别。

对您的问题的简短回答是您应该使用 TypeVars 或 Sequence——使用 List[Union[int, float]] 实际上可能会在您的代码中引入错误!

简而言之,问题是根据 PEP 484 类型系统(以及许多其他类型系统——例如 Java、C#.. .).您正在尝试使用该列表,就好像它是 covariant 一样。您可以了解有关协变性和不变性的更多信息 here and here,但也许您的代码可能不安全的示例可能会有用。

考虑以下代码:

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!? 

如果允许此代码进行类型检查,我们就破坏了我们的代码!任何依赖于 foo 类型为 List[int] 的代码现在都会中断。

或者更准确地说,尽管 intUnion[int, float] 的合法子类型,但这并不意味着 List[int]List[Union[int, float]] 的子类型,反之亦然相反。


如果我们同意这种行为(我们同意 quick_sort 决定将任意整数或浮点数注入输入数组),解决方法是手动注释 fooList[Union[int, float]]:

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

# Or, in Python 3.6+
foo: List[Union[int, float]] = [1, 2, 3, 4]

也就是说,预先声明 foo 尽管只包含整数,但也意味着也包含浮点数。这可以防止我们在调用 quick_sort 后错误地使用列表,从而完全回避问题。

在某些情况下,这可能是您想要做的。不过,对于这种方法,可能不是。


如果我们接受这种行为,并希望quick_sort保留列表中最初的任何类型,我会想到两个解决方案:

第一种是使用 协变 类型而不是列表——例如,Sequence:

from typing import Union, Sequence

Num = Union[int, float]

def quick_sort(arr: Sequence[Num]) -> Sequence[Num]:
    return arr

事实证明,Sequence 或多或少类似于 List,只是它是不可变的(或者更准确地说,Sequence 的 API 不包含任何让您改变列表的方法)。这让我们可以安全地避开上面的错误。

第二种解决方案是更精确地键入数组,并坚持必须包含所有整数或所有浮点数,不允许两者混合。我们可以使用 TypeVars with value restrictions:

from typing import Union, List, TypeVar 

# Note: The informal convention is to prefix all typevars with
# either 'T' or '_T' -- so 'TNum' or '_TNum'.
TNum = TypeVar('TNum', int, float)

def quick_sort(arr: List[TNum]) -> List[TNum]:
    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)

这也可以防止我们像上面那样意外 "mixing" 类型。

我建议使用第二种方法 -- 它更精确一些,并且可以防止您在通过快速排序函数传递列表时丢失有关列表包含的确切类型的信息。