问题描述
我的代码如下:
from typing import Tuple
a: Tuple[int, int] = tuple(sorted([1, 3]))
Mypy 告诉我:
赋值中的不兼容类型(表达式的类型为Tuple[int,...]",变量的类型为Tuple[int, int]")
我做错了什么?为什么 Mypy 无法确定排序后的元组将返回正好两个整数?
What am I doing wrong? Why can't Mypy figure out that the sorted tuple will give back exactly two integers?
推荐答案
对 sorted
的调用会生成一个 List[int]
,其中不包含有关长度的信息.因此,从它生成一个元组也没有关于长度的信息.元素的数量根本取决于您使用的类型.
The call to sorted
produces a List[int]
which carries no information about length. As such, producing a tuple from it also has no information about the length. The number of elements simply is undefined by the types you use.
在这种情况下,您必须告诉类型检查器信任您.使用 # type: ignore
或 cast
无条件地接受目标类型为有效:
You must tell your type checker to trust you in such cases. Use # type: ignore
or cast
to unconditionally accept the target type as valid:
# 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])))
或者,创建一个长度感知排序:
Alternatively, create a lenght-aware sort:
def sort_pair(a: T, b: T) -> Tuple[T, T]:
return (a, b) if a <= b else (b, a)
这篇关于如何让 Mypy 意识到对两个整数进行排序会返回两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!