我在我的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
0.2 开始忽略# type: ignore
的类型错误(请参阅问题 #500,忽略特定行(:
PEP 484 使用
# type: ignore
忽略特定行上的类型错误...此外,使用靠近文件顶部的
# type: ignore
[跳过] 完全检查该文件。来源:mypy#500。另请参阅 mypy 文档。
另外# mypy: ignore-errors
在文件顶部,您要忽略所有错误都可以工作,如果您使用的是shebang,并且编码行应如下所示:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# mypy: ignore-errors
格万罗苏姆评论
当然,这个问题的答案是在行尾添加# type:ignore
,希望mypy忽略它。
当我在谷歌上搜索如何忽略 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
我用过
# type: ignore # noqa: F401
忽略给我 F401 错误的一行。我相信你可以把它扩展到其他错误代码
请注意,# type: ignore
将忽略所有错误。如果您不希望这样做,请仅忽略特定的错误代码。
例:
def knows(a: int, b: int) -> bool: # type: ignore[empty-body]
pass