首页 > 解决方案 > 在 mypy 中动态检查元组长度

问题描述

我有使用不同长度元组类型联合的程序,它动态检查元组的长度以优化类型。Mypy 无法识别出在这种动态检查之后更准确地知道变量的类型,因此它会报告虚假类型错误。如何以 mypy 理解的方式动态检查元组长度?

在下面的示例中,mypy 在用作两个值的元组时会报告错误shape,即使上一行的断言确保其类型为Tuple[int, int].

from typing import *

def f(dimensions: int,
      shape: Union[Tuple[int, int], Tuple[int, int, int]]):
    if dimensions == 2:
        assert len(shape) == 2
        height, width = shape
        print(height * width)

mypy 在元组拆包行报错:error: Too many values to unpack (2 expected, 3 provided).

我将 mypy 0.720 与 Python 3.7.4 一起使用。

标签: pythontuplesmypy

解决方案


您应该使用显式强制转换(另请参阅此问题,由@aaron 的评论提供):

if dimensions == 2:
    assert len(shape) == 2
    shape = cast(Tuple[int, int], shape)
    height, width = shape
    print(height * width)

此外,正如其他答案中指出的那样,这个dimension论点是多余的,你可以这样做

def f2(shape: Union[Tuple[int, int], Tuple[int, int, int]]):
    dimensions: int = len(shape)
    if dimensions == 2:
        shape = cast(Tuple[int, int], shape)
        height, width = shape
        print(height * width)         

推荐阅读