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

How can mypy ignore a single line in a source file?

我正在使用 mypy in my python project for type checking. I'm also using PyYAML for reading and writing the project configuration files. Unfortunately, when using the 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

version 0.2 (see issue #500, Ignore specific lines 起,您可以使用 # type: ignore 忽略类型错误):

PEP 484 uses # type: ignore for ignoring type errors on particular lines ...

Also, using # type: ignore close to the top of a file [skips] checking that file altogether.

Source: mypy#500. See also the mypy documentation.

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

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

Gvanrossum comment

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

当我 google 了解如何忽略 Django 迁移的文件时,
这个问题被推荐给我好几次了

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