'Prevent mypy errors in platform dependent python code
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
win32apidoesn't exist, - "module has no attribute ..." because the
winregmodule 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: ignoreeverywhere --ignore-missing-imports
Are there any better solutions for this?
Solution 1:[1]
Ok, after checking the Docs as @SUTerliakov so kindly suggested, it seems that i have to change my
if platform.system() == "Windows"
to this, semantically identical check:
if sys.platform == "win32"
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ChrisB |
