如何让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告诉我:
分配中的类型不兼容(表达式的类型为"Tuple [int, ...],变量的类型为" Tuple [int,int])
Incompatible types in assignment (expression has type "Tuple[int, ...]", variable has type "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]
,该cc>不包含有关长度的信息.这样,从中生成元组也没有有关长度的信息.元素的数量完全不受您使用的类型的定义.
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意识到对两个整数进行排序会返回两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!