我可以在线抑制 mypy 错误吗?
Can I suppress mypy errors in-line?
我最近错误地打开了我的 $PYTHONSTARTUP
文件并启用了 mypy
语法检查。结果,我开始收到此错误:
startup.py|79 col 2 error| Incompatible types in assignment (expression has type "HistoryPrompt", variable has type "str")
第 79 行:
sys.ps1 = HistoryPrompt()
我马上想到,"By Jove, mypy
! You're entirely correct! And yet, that is exactly what I want to do, so you're also wrong!"
我去看看是否有某种 sys
模块的 "stub",但找不到任何东西。我猜 mypy
是通过查看存储在变量中的值来确定类型的(默认是“>>>”,这是一个 str
)。
在现实中,当然,类型需要是不存在的typing.Stringifiable
,表示一个将响应str(x)
的对象。
到达那个死胡同后,我开始寻找一种方法告诉 mypy
抑制错误。很多其他工具都支持 # noqa: xxx
,我认为 必须 是什么,对吧?
错了。或者至少,我在我的版本中找不到它,它是:mypy 0.670
所以我设计了一个 hack 聪明的解决方法:
import typing
# Work around mypy error: Incompatible types in assignment
suppress_mypy_error: typing.Any = HistoryPrompt()
sys.ps1 = suppress_mypy_error
我的问题是:是否有 在线(最佳)或 mypy.ini
抑制此特定错误的方法,或通过提交 PR 至python/mypy
,或者...?
要在特定行上显式禁止 MyPy,请添加 # type: ignore
.
形式的注释
要为整个模块抑制 MyPy,请在模块顶部添加相同的注释。
我最近错误地打开了我的 $PYTHONSTARTUP
文件并启用了 mypy
语法检查。结果,我开始收到此错误:
startup.py|79 col 2 error| Incompatible types in assignment (expression has type "HistoryPrompt", variable has type "str")
第 79 行:
sys.ps1 = HistoryPrompt()
我马上想到,"By Jove, mypy
! You're entirely correct! And yet, that is exactly what I want to do, so you're also wrong!"
我去看看是否有某种 sys
模块的 "stub",但找不到任何东西。我猜 mypy
是通过查看存储在变量中的值来确定类型的(默认是“>>>”,这是一个 str
)。
在现实中,当然,类型需要是不存在的typing.Stringifiable
,表示一个将响应str(x)
的对象。
到达那个死胡同后,我开始寻找一种方法告诉 mypy
抑制错误。很多其他工具都支持 # noqa: xxx
,我认为 必须 是什么,对吧?
错了。或者至少,我在我的版本中找不到它,它是:mypy 0.670
所以我设计了一个 hack 聪明的解决方法:
import typing
# Work around mypy error: Incompatible types in assignment
suppress_mypy_error: typing.Any = HistoryPrompt()
sys.ps1 = suppress_mypy_error
我的问题是:是否有 在线(最佳)或 mypy.ini
抑制此特定错误的方法,或通过提交 PR 至python/mypy
,或者...?
要在特定行上显式禁止 MyPy,请添加 # type: ignore
.
要为整个模块抑制 MyPy,请在模块顶部添加相同的注释。