agh*_*ast 6 python python-3.x mypy
我最近犯了在启用语法检查的情况下打开$PYTHONSTARTUP文件的错误mypy。结果,我开始收到此错误:
startup.py|79 col 2 error| Incompatible types in assignment (expression has type "HistoryPrompt", variable has type "str")
Run Code Online (Sandbox Code Playgroud)
在第 79 行:
sys.ps1 = HistoryPrompt()
Run Code Online (Sandbox Code Playgroud)
我立刻想,“天哪,mypy!你完全正确!然而,这正是我想要做的,所以你也错了!”
我去看看模块是否有某种“存根” sys,但找不到任何东西。我猜这mypy是通过查看存储在变量中的值来确定类型(默认为“>>>”,即 a str)。
在现实中,当然,类型需要是不存在的typing.Stringifiable,表明一个对象将响应str(x)。
到了那个死胡同后,我开始寻找一种方法mypy来抑制错误。这么多其他工具支持# noqa: xxx,我想一定有什么,对吧?
错误的。或者至少,我在我的版本中找不到它,即:mypy 0.670
所以,我设计了一个黑客巧妙的变通办法:
import typing
# Work around mypy error: Incompatible types in assignment
suppress_mypy_error: typing.Any = HistoryPrompt()
sys.ps1 = suppress_mypy_error
Run Code Online (Sandbox Code Playgroud)
我的问题是:有没有办法在线(最好)mypy.ini、或通过向python/mypy、或...提交 PR 来抑制此特定错误?
0az*_*0az 12
要在特定行上显式禁止 MyPy,请添加形式为 的注释# type: ignore。
要取消整个模块的 MyPy,请在模块顶部添加相同的注释。
来源:https : //mypy.readthedocs.io/en/latest/common_issues.html#spurious-errors-and-locally-silencing-the-checker
Ben*_*rth 11
我更喜欢基于两件事来抑制 mypy 错误:
例如,# type: ignore [no-untyped-call]:
# ignore mypy error because azure has broken type hints.
# See https://github.com/Azure/azure-sdk-for-python/issues/20083 (the issue is closed but the problem remains)
exception = azure.core.exceptions.ResourceNotFoundError("Test") # type: ignore [no-untyped-call]
Run Code Online (Sandbox Code Playgroud)
no-untyped-call您可以通过以下方式配置 mypy 来找出 mypy 输出中的“错误代码”(例如):
pyproject.toml[tool.mypy]
show_error_codes = true
Run Code Online (Sandbox Code Playgroud)
mypy.ini[mypy]
show_error_codes = True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3640 次 |
| 最近记录: |