How can mypy ignore a single line in a source file

2020-06-30 08:50发布

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

2条回答
2楼-- · 2020-06-30 09:23

Also # mypy: ignore-errors at the top of the file you want to ignore all works, if you are using shebang and coding lines should be like this:

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

Gvanrossum comment

查看更多
登录 后发表回答