【问题标题】:How to get Mypy to realize that sorting two ints gives back two ints如何让 Mypy 意识到对两个整数进行排序会返回两个整数
【发布时间】:2019-10-21 14:30:16
【问题描述】:

我的代码如下:

from typing import Tuple

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

Mypy 告诉我:

赋值中不兼容的类型(表达式的类型为“Tuple[int, ...]”,变量的类型为“Tuple[int, int]”)

我做错了什么?为什么 Mypy 无法确定排序后的元组将返回正好两个整数?

【问题讨论】:

    标签: python-3.x int tuples typechecking mypy


    【解决方案1】:

    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])))
    

    或者,创建一个长度感知排序:

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

    【讨论】:

    • 现在我再次看到这一点,我想我们也可以将cast 排序为正确的类型,而不是告诉类型检查器忽略。
    • 是的,您可以使用演员表。请注意,a: T = b # type: ignorea = cast(T, b) 等效于键入(cast 忽略所有先前的类型信息)。但是,cast 会带来一些运行时开销。
    猜你喜欢
    • 2014-12-29
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多