mypy 如何忽略源文件中的一行?

问题描述 投票:0回答:5

我在 python 项目中使用 mypy 进行类型检查。我还使用 PyYAML 来读取和写入项目配置文件。不幸的是,当使用 PyYAML 文档中推荐的导入机制时,这会在尝试导入本机库的 try/ except 子句中生成虚假错误: from yaml import load, dump try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper

在我的系统上
CLoader

CDumper

 不存在,这会导致错误 
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
5个回答
321
投票
开始,您可以使用

# type: ignore

 忽略类型错误(请参阅问题 
#500,忽略特定行):

PEP 484
使用

# type: ignore 忽略特定行上的类型错误

 ...
此外,在文件顶部附近使用 # type: ignore

[跳过]完全检查该文件


来源:

mypy#500

。另请参阅 mypy 文档

如果您想忽略整个文件中的
all

40
投票
# mypy: ignore-errors

也可以使用。如果您使用 shebang 和编码线,则应按如下方式排序:

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

来源:Gvanrossum 对相关 mypy 问题的评论


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


11
投票
这个问题被推荐给我好几次了。

所以我发布了一个关于如何忽略 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


我用过

# type: ignore # noqa: F401

3
投票

请注意,
# type: ignore

将忽略

所有

2
投票

示例:

def knows(a: int, b: int) -> bool:  # type: ignore[empty-body]
    pass

上面忽略了函数 

empty-body

的错误代码

knows
。如果您想忽略整个文件的特定错误,请将以下内容放在文件顶部,就在导入之后:

# mypy: disable-error-code="empty-body"

    

© www.soinside.com 2019 - 2024. All rights reserved.