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

2024-04-28 07:51:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python项目中使用mypy进行类型检查。我还使用PyYAML来读写项目配置文件。不幸的是,当使用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忽略这行的错误?我希望我能做点这样的事让我的孩子跳过这一行:

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

Tags: 项目fromimportyamlas错误loadloader