为什么我会收到 mypy no overrides of "zip" matches argument 错误?

2024-03-28

我有一个带有方法的类:

class TimeUtilitiesTestCase():
    def test_date_and_delta(self) -> None:
        """Tests date_and_delta utility method."""
        now = datetime.datetime.now()
        tdelta = datetime.timedelta
        int_tests = (3, 29, 86399, 86400, 86401 * 30)
        date_tests = [now - tdelta(seconds=x) for x in int_tests]
        td_tests = [tdelta(seconds=x) for x in int_tests]
        results = [(now - tdelta(seconds=x), tdelta(seconds=x)) for x in int_tests]
        for test in (int_tests, date_tests, td_tests):
            for arg, result in zip(test, results):
                dtime, delta = humanizer_portugues.time.date_and_delta(arg)
                self.assertEqualDatetime(dtime, result[0])
                self.assertEqualTimedelta(delta, result[1])
        self.assertEqual(humanizer_portugues.time.date_and_delta("NaN"), (None, "NaN"))

我正在运行严格的 mypy 检查(配置here https://github.com/staticdev/humanizer-portugues/blob/858db670671bf54d18ffcbbf63a396be863e5f53/mypy.ini),我收到错误:

error: No overload variant of "zip" matches argument
types "object", "List[Tuple[datetime, timedelta]]"  [call-overload]
                for arg, result in zip(test, results):
                                   ^
note: Possible overload variants:
note:     def [_T1, _T2] zip(*iterables: Tuple[_T1, _T2]) -> Tuple[Tuple[_T
1, ...], Tuple[_T2, ...]]
note:     def [_T1, _T2, _T3] zip(*iterables: Tuple[_T1, _T2, _T3]) -> Tupl
e[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...]]
note:     <3 more similar overloads not shown, out of 10 total overloads>

如果你想完全重现错误,你可以克隆分支strict-mypy with: git clone -b strict-mypy https://github.com/staticdev/humanizer-portugues.git

我尝试改变results从列表到也是一个元组,但这个错误并没有消失。

我这里打字怎么不正确?


编者注:
可以通过以下最小示例重现此问题:

def bug_repr() -> None:
    ints = [1, 2]
    floats = [3.14, 2.72]
    strings = ['a', 'b']
    for numeric_list in [ints, floats]:
        for number, string in zip(numeric_list, strings):  # <-- error here
            pass

这给出了同样的错误:

main.py:6: error: No overload variant of "zip" matches argument types "object", "List[str]"
main.py:6: note: Possible overload variants:
main.py:6: note:     def [_T1, _T2] zip(*iterables: Tuple[_T1, _T2]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...]]
main.py:6: note:     def [_T1, _T2, _T3] zip(*iterables: Tuple[_T1, _T2, _T3]) -> Tuple[Tuple[_T1, ...], Tuple[_T2, ...], Tuple[_T3, ...]]
main.py:6: note:     <3 more similar overloads not shown, out of 10 total overloads>
Found 1 error in 1 file (checked 1 source file)

您可以在以下位置重现此内容.


使用您的最小示例:

问题是,MyPy 推断出的类型太窄,即List[int] and List[float]然后它无法推断类型List of something for numeric_list。一般来说,当你放入不同的东西时,容器和静态类型安全会出现问题。例如,您输入了一个浮点数和一个整数,那么静态分析如何知道您要取出什么?看关于方差的文档 https://mypy.readthedocs.io/en/latest/common_issues.html#variance

但是你可以声明一个更通用的类型,使用联合类型 https://mypy.readthedocs.io/en/latest/kinds_of_types.html?highlight=Union#union-types,声明它可能包含多种类型。

from typing import Union, List

def bug_repr() -> None:
    ints: List[Union[int, float]] = [1, 2]
    floats: List[Union[int, float]] = [3.14, 2.72]
    strings = ['a', 'b']
    for numeric_list in [ints, floats]:
        for number, string in zip(numeric_list, strings):
            pass

或者,您可以将其声明为列表(或序列),而不指定里面的内容:

from typing import List

def bug_repr() -> None:
    ints: List = [1, 2]
    floats: List = [3.14, 2.72]
    strings = ['a', 'b']
    for numeric_list in [ints, floats]:
        for number, string in zip(numeric_list, strings):
            pass

但我不确定会推断出什么类型number在内循环中。

(注意,您还可以使用Sequence作为更通用的类型而不是List)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我会收到 mypy no overrides of "zip" matches argument 错误? 的相关文章

  • 多重处理:如何从子进程重定向标准输出?

    注意 我见过multiprocessing Process 的日志输出 https stackoverflow com questions 1501651 log output of multiprocessing process 不幸的是
  • 如何在groupby之后将pandas数据框拆分为许多列

    我希望能够在 pandas 中使用 groupby 按列对数据进行分组 然后将其拆分 以便每个组都是数据框中自己的列 e g time data 0 1 2 0 1 2 3 0 2 3 4 0 3 1 2 1 4 2 3 1 5 3 4 1
  • 如何 json_normalize() df 中的特定字段并保留其他列? [复制]

    这个问题在这里已经有答案了 这是我的简单示例 我的实际数据集中的 json 字段非常嵌套 因此我一次解压一层 我需要在 json normalize 之后保留数据集上的某些列 https pandas pydata org docs ref
  • 如何用spaCy获取依赖树?

    我一直在尝试寻找如何使用 spaCy 获取依赖树 但我找不到任何有关如何获取树的信息 只能在如何导航树 https spacy io usage examples subtrees 如果有人想轻松查看 spacy 生成的依赖关系树 一种解决
  • 将 Django 表单中的所有 CharField 表单字段输入转换为小写

    我使用 Django 表单进行用户注册 用户可以在其中输入优惠券代码 我希望在优惠券代码字段中输入的所有字符都转换为小写 我尝试过在保存方法 自定义清理方法和自定义验证器中使用 lower 但这些方法没有运气 下面是我的代码 class S
  • 如何在 openpyxl 中设置或更改表格的默认高度

    我想通过openpyxl更改表格高度 并且我希望首先默认一个更大的高度值 然后我可以设置自动换行以使我的表格更漂亮 但我不知道如何更改默认高度 唯一的到目前为止 我知道更改表格高度的方法是设置 row dimension idx heigh
  • 基于 True/False 值的 Python 优雅赋值

    我想根据三个布尔值中的值设置一个变量 最直接的方法是 if 语句后跟一系列 elif if a and b and c name first elif a and b and not c name second elif a and not
  • 使用 Python 解析 XML,解析外部 ENTITY 引用

    在我的 S1000D xml 中 它指定了一个带有对公共 URL 的引用的 DOCTYPE 该 URL 包含对包含所有有效字符实体的许多其他文件的引用 我使用 xml etree ElementTree 和 lxml 尝试解析它并得到解析错
  • 如何将同步函数包装在异步协程中?

    我在用着aiohttp https github com aio libs aiohttp构建一个 API 服务器 将 TCP 请求发送到单独的服务器 发送 TCP 请求的模块是同步的 对于我来说是一个黑匣子 所以我的问题是这些请求阻塞了整
  • Pandas,按最大返回值进行分组 AssertionError:

    熊猫有问题 我想听听你的意见 我有这个数据框 我需要在其中获取最大值 代码就在下面 df stack pd DataFrame 1 0 2016 0 NonResidential Hotel 98101 0 DOWNTOWN 47 6122
  • 如何在python中递归复制目录并覆盖全部?

    我正在尝试复制 home myUser dir1 及其所有内容 及其内容等 home myuser dir2 在Python中 此外 我希望副本覆盖中的所有内容dir2 It looks like distutils dir util co
  • 使用 pandas 绘制带有误差线的条形图

    我正在尝试从 DataFrame 生成条形图 如下所示 Pre Post Measure1 0 4 1 9 这些值是我从其他地方计算出来的中值 我还有它们的方差和标准差 以及标准误差 我想将结果绘制为具有适当误差线的条形图 但指定多个误差值
  • DRF:以编程方式从 TextChoices 字段获取默认选择

    我们的网站是 Vue 前端 DRF 后端 在一个serializer validate 方法 我需要以编程方式确定哪个选项TextChoices类已被指定为模型字段的默认值 TextChoices 类 缩写示例 class PaymentM
  • 使用Python重命名目录中的多个文件

    我正在尝试使用以下 Python 脚本重命名目录中的多个文件 import os path Users myName Desktop directory files os listdir path i 1 for file in files
  • 获取运行云功能的运行时服务帐户

    有没有办法以编程方式从云功能获取运行时服务帐户的电子邮件 我知道我可以 猜测 默认的 App Engine 帐户 因为它始终是 appspot gserviceaccount com 但这不是我想要的 我本来期待有一些环境变量 https
  • bool() 和operator.truth() 有什么区别?

    bool https docs python org 3 library functions html bool and operator truth https docs python org 3 library operator htm
  • 如何将 Pandas Dataframe 中的字符串转换为字符列表或数组?

    我有一个名为的数据框data 其中一列包含字符串 我想从字符串中提取字符 因为我的目标是对它们进行一次性编码并使之可用于分类 包含字符串的列存储在预测因子如下 predictors pd DataFrame data columns Seq
  • 将数组从 .npy 文件读入 Fortran 90

    我使用 Python 以二维数组 例如 X 的形式生成一些初始数据 然后使用 Fortran 对它们进行一些计算 最初 当数组大小约为 10 000 x 10 000 时 np savetxt 在速度方面表现良好 但是一旦我开始增加数组的维
  • Python 中的迭代器 (iter()) 函数。 [关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 对于字典 我可以使用iter 用于迭代字典的键 y x 10 y 20 for val in iter y print val 当
  • 从 Flask 中的 S3 返回 PDF

    我正在尝试在 Flask 应用程序的浏览器中返回 PDF 我使用 AWS S3 来存储文件 并使用 boto3 作为与 S3 交互的 SDK 到目前为止我的代码是 s3 boto3 resource s3 aws access key id

随机推荐