python - 在 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 一起使用。
解决方案
您应该使用显式强制转换(另请参阅此问题,由@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)
推荐阅读
- haskell - 为什么在 'do{ let{ the= Just "Hi!"}; 中输出 'Nothing' _ <- 序列 [the,Nothing]; 纯粹的“不可能!” }'
- anylogic - 在物流模型中上传时间数据集
- javascript - 为什么我的 javascript 代码中的变量不起作用?
- php - 使用 http_build_query 时,如何将 '%2' 替换为 '+'?
- scala - 将 spark 数据框列值替换为随机值(例如 UUID)
- android - 由于 jenkins 触发的 aws 实例上未接受某些许可证,因此无法安装以下 Android SDK 包
- python - 不明白“while not”循环是如何工作的
- c++ - StringCch* 函数和 Cstring
- python - 有一个字符串并尝试输入该输入表视图
- tensorflow - 具有多个独立输出的二进制分类