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

我们两清 提交于 2019-12-12 09:30:44

问题


I'm using 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 this generates a spurious error in a try/except clause that attempts to import native libraries:

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

On my system CLoader and CDumper aren't present, which results in the errors error: Module 'yaml' has no attribute 'CLoader' and error: Module 'yaml' has no attribute 'CDumper'.

Is there a way to have mypy ignore errors on this line? I was hoping that I could do something like this to have mypy skip that line:

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

回答1:


You can do this with # type: ignore as of 0.57 (see #500, Ignore specific lines):

PEP 484 uses # type: ignore for ignoring type errors on particular lines, and mypy should support that. Also, using # type: ignore close to the top of a file should skip checking that file altogether.



来源:https://stackoverflow.com/questions/49220022/how-can-mypy-ignore-a-single-line-in-a-source-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!