如何让 Mypy 意识到对两个整数进行排序会返回两个整数 [英] How to get Mypy to realize that sorting two ints gives back two ints

查看:42
本文介绍了如何让 Mypy 意识到对两个整数进行排序会返回两个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

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],其中不包含有关长度的信息.因此,从它生成一个元组也没有关于长度的信息.元素的数量根本取决于您使用的类型.

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: ignorecast 无条件地接受目标类型为有效:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆