如何避免 mypy 检查显式排除但导入的模块_无需_手动添加 `type:ignore` (自动生成)?

问题描述 投票:0回答:2

在下面的MWE中,我有两个文件/模块:

  1. main.py
    这是并且应该用 mypy
  2. 检查
  3. importedmodule.py
    不应进行类型检查,因为它是自动生成的。 这个文件是自动生成的,我不想添加
    type:ignore

MyPy 命令

$ mypy main.py --exclude '.*importedmodule.*'
$ mypy --version
mypy 0.931

主.py

"""
This should be type checked
"""

from importedmodule import say_hello

greeting = say_hello("Joe")
print(greeting)

导入模块.py

"""
This module should not be checked in mypy, because it is excluded
"""


def say_hello(name: str) -> str:
    # This function is imported and called from my type checked code
    return f"Hello {name}!"


def return_an_int() -> int:
    # ok, things are obviously wrong here but mypy should ignore them
    # also, I never expclitly imported this function
    return "this is a str, not an int" # <-- this is line 14 referenced in the mypy error message

但是 MyPy 抱怨该函数甚至没有导入到 main.py 中:

importedmodule.py:14:错误:返回值类型不兼容(得到“str”,预期“int”) 在 1 个文件中发现 1 个错误(检查了 1 个源文件)

我的排除有什么问题?

python mypy
2个回答
3
投票

为了让SUTerliakov对你的问题的评论更加明显,我想在这里再次更详细地介绍它。

pyproject.toml
文件中,您可以在其他 mypy 配置下面插入以下内容

[[tool.mypy.overrides]]
module = "importedmodule"
ignore_errors = true

使用此配置,您将忽略来自上述模块的所有错误。

通过使用通配符,您还可以忽略目录中的所有模块:

[[tool.mypy.overrides]]
module = "importedpackage.*"
ignore_errors = true

1
投票

来自 mypy 文档

特别是,

--exclude
不影响mypy的导入跟随。您可以使用每个模块
follow_imports
配置选项来额外避免 mypy 跟踪导入并检查您不希望检查的代码。

不幸的是,似乎没有一个 cli 选项可以对导入模块中未使用的函数禁用 mypy。导入模块时,mypy 会分析所有模块。 static 分析器不会检查函数是否被使用。

但是,您可以消除这些导入模块中创建的任何错误

$ mypy main.py --follow-imports silent
Success: no issues found in 1 source file
$ mypy main.py --follow-imports skip
Success: no issues found in 1 source file
© www.soinside.com 2019 - 2024. All rights reserved.