如何让 Mypy 意识到对两个整数进行排序会返回两个整数

How to get Mypy to realize that sorting two ints gives back two ints

我的代码如下:

from typing import Tuple

a: Tuple[int, int] = tuple(sorted([1, 3]))

Mypy 告诉我:

Incompatible types in assignment (expression has type "Tuple[int, ...]", variable has type "Tuple[int, int]")

我做错了什么?为什么 Mypy 不能计算出排序后的元组将返回恰好两个整数?

sorted 的调用产生一个 List[int],它不包含任何长度信息。因此,从中生成元组也没有关于长度的信息。元素的数量只是由您使用的类型未定义。

在这种情况下,您必须告诉您的类型检查器信任您。使用 # type: ignorecast 无条件接受目标类型为有效:

# ignore mismatch by annotation
a: Tuple[int, int] = tuple(sorted([1, 3]))  # type: ignore
# ignore mismatch by cast
a = cast(Tuple[int, int], tuple(sorted([1, 3])))

或者,创建一个 length-aware 排序:

 def sort_pair(a: T, b: T) -> Tuple[T, T]:
     return (a, b) if a <= b else (b, a)