防止平台依赖的Python代码中的mypy错误
我有类似于以下python代码的内容:
import platform
if platform.system() == "Windows":
import winreg
import win32api
def do_cross_platform_thing() -> None:
if platform.system() == "Windows":
# do some overly complicated windows specific thing with winreg and win32api
else:
# do something reasonable for everyone else
现在,在Linux上,mypy
抱怨
- 它缺少导入,因为
win32api
不存在, - ”模块没有属性。 ..“因为
winreg
模块是 定义,但基本上是禁用的(所有代码均为“ Windows”检查后面)。
有什么合理的方法可以解决吗?我当前的解决方案是
- 垃圾邮件
#类型:ignore
无处不在 - 忽略 - 密码imports
有什么更好的解决方案吗?
I have something akin to the following piece of python code:
import platform
if platform.system() == "Windows":
import winreg
import win32api
def do_cross_platform_thing() -> None:
if platform.system() == "Windows":
# do some overly complicated windows specific thing with winreg and win32api
else:
# do something reasonable for everyone else
Now, on linux, mypy
complains that
- it's missing imports because
win32api
doesn't exist, - "module has no attribute ..." because the
winreg
module is
defined, but basically disabled (all code is behind an 'is windows' check).
Is there any reasonable way to deal with this ? My current solution is
- spamming
# type: ignore
everywhere --ignore-missing-imports
Are there any better solutions for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,检查
语义上相同的检查更改为:
仅此第二版触发了一些魔术的内置特殊情况。
将其标识为平台检查,而忽略了分支
适用于其壁画。
Ok, after checking the Docs as @SUTerliakov so kindly suggested,
it seems that i have to change my
to this, semantically identical check:
Only this second version triggers some magic builtin mypy special case that
identifies this as a platform check and ignores the branch not
applicable to its plattform.
您可以使用
语法以mypy 1.4 (发布2023-06-20,pr 15164 )。用您从Mypy获得的错误代码替换
某些元代码
。从PR中获取的示例:在上面的
中忽略[import]
忽略导入错误(例如,在python 3.7上,其中 graphlib 不存在)和忽略[unused-ignore]
忽略由warn_unused_ignores Mypy设置,例如Python 3.9此模块可用。
You may use the
syntax introduced in Mypy 1.4 (Released 2023-06-20, PR 15164). Replace the
some-mypy-code
with the error code which you get from mypy. Example taken from the PR:In the above, the
ignore[import]
ignores the import error (on Python 3.7 for example, where graphlib does not exist) andignore[unused-ignore]
ignores the error caused by thewarn_unused_ignores
mypy setting on e.g. Python 3.9 where this module is available.