我在 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
从
# mypy: ignore-errors
也可以使用。如果您使用 shebang 和编码线,则应按如下方式排序:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# mypy: ignore-errors
来源:Gvanrossum 对相关 mypy 问题的评论
当然,这个问题的答案是在行尾添加 # type:ignore
希望 mypy 忽略它。
所以我发布了一个关于如何忽略 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
请注意,
# type: ignore
将忽略
所有示例:
def knows(a: int, b: int) -> bool: # type: ignore[empty-body]
pass
上面忽略了函数 empty-body
的错误代码
knows
。如果您想忽略整个文件的特定错误,请将以下内容放在文件顶部,就在导入之后:
# mypy: disable-error-code="empty-body"