【问题标题】:How can mypy ignore a single line in a source file?mypy 如何忽略源文件中的一行?
【发布时间】:2018-08-19 13:48:40
【问题描述】:

我在我的 python 项目中使用mypy 进行类型检查。我还使用 PyYAML 来读取和写入项目配置文件。不幸的是,当使用recommended import mechanism from the PyYAML documentation 时,这会在尝试导入本机库的 try/except 子句中产生虚假错误:

from yaml import load, dump
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

在我的系统上 CLoaderCDumper 不存在,这导致错误 error: Module 'yaml' has no attribute 'CLoader'error: Module 'yaml' has no attribute 'CDumper'

有没有办法让 mypy 忽略这一行的错误?我希望我可以做这样的事情让 mypy 跳过那一行:

from yaml import load, dump
try:
    from yaml import CLoader as Loader, CDumper as Dumper  # nomypy
except ImportError:
    from yaml import Loader, Dumper

【问题讨论】:

    标签: python types mypy


    【解决方案1】:

    version 0.2 开始,您可以忽略# type: ignore 的类型错误(参见问题#500, Ignore specific lines):

    PEP 484 使用# type: ignore 忽略特定行上的类型错误 ...

    此外,在文件顶部附近使用# type: ignore[跳过] 完全检查该文件

    来源:mypy#500。另请参阅mypy documentation

    【讨论】:

    • 知道如何将# type: ignore 放在上面的行吗?
    • 我的探矿者 linter 需要一定的长度
    • @GregHilston 您可以使用 `\` 或括号拆分行并将注释写入发生 mypy 错误的行。
    • 更具体地说,MyPy 支持使用type: ignore[code, ...] 指定要忽略的错误代码。见mypy.readthedocs.io/en/stable/…。在这种情况下,它将是# type: ignore[attr-defined]
    • 感谢@GinoMempin,对于其他情况,您可以运行带有--show-error-codes 标志的mypy 以查看代码
    【解决方案2】:

    还有# mypy: ignore-errors在文件顶部你想忽略所有作品,如果你使用shebang,编码行应该是这样的:

    #!/usr/bin/env python 
    #-*- coding: utf-8 -*-
    # mypy: ignore-errors
    

    Gvanrossum comment

    【讨论】:

    • 请注意此忽略 whole 文件上的 all 错误,而不仅仅是像 OP 所询问的那样的单行错误。
    • 这就是我写“全部”的原因,确定这不是 OP 想要的公认答案,而只是对这个线程的补充。如果您想添加到答案中,请编写编辑或其他答案:)
    • 是的,这只是对任何看到此答案的人的警告:)
    【解决方案3】:

    当然,这个问题的答案是在希望mypy忽略它的行尾加上# type:ignore

    当我在谷歌上寻找如何忽略 django 迁移文件时,
    这个问题被我多次推荐过。

    所以我发布了一个关于如何忽略 Django 迁移的答案:

    # mypy.ini
    [mypy-*.migrations.*]
    ignore_errors = True
    

    对于mypy>=0.910,支持pyproject.toml,可以设置如下:

    [tool.mypy]
    python_version = 3.8
    ignore_missing_imports = true
    
    [[tool.mypy.overrides]]
    module = "*.migrations.*"
    ignore_errors = true
    

    【讨论】:

    • 请注意,这将忽略整个文件所有类型的错误的错误,而不仅仅是特定的错误行(OP最初询问的)。
    猜你喜欢
    • 2018-12-13
    • 2016-09-18
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2012-11-09
    • 2022-07-23
    相关资源
    最近更新 更多