在下面的MWE中,我有两个文件/模块:
main.py
这是并且应该用 mypyimportedmodule.py
不应进行类型检查,因为它是自动生成的。 这个文件是自动生成的,我不想添加type:ignore
。$ mypy main.py --exclude '.*importedmodule.*'
$ mypy --version
mypy 0.931
"""
This should be type checked
"""
from importedmodule import say_hello
greeting = say_hello("Joe")
print(greeting)
"""
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 个源文件)
我的排除有什么问题?
为了让SUTerliakov对你的问题的评论更加明显,我想在这里再次更详细地介绍它。
在
pyproject.toml
文件中,您可以在其他 mypy 配置下面插入以下内容
[[tool.mypy.overrides]]
module = "importedmodule"
ignore_errors = true
使用此配置,您将忽略来自上述模块的所有错误。
通过使用通配符,您还可以忽略目录中的所有模块:
[[tool.mypy.overrides]]
module = "importedpackage.*"
ignore_errors = true
来自 mypy 文档,
特别是,
不影响mypy的导入跟随。您可以使用每个模块--exclude
配置选项来额外避免 mypy 跟踪导入并检查您不希望检查的代码。follow_imports
不幸的是,似乎没有一个 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