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
win32api doesn't exist,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
# type: ignore everywhere--ignore-missing-importsAre there any better solutions for this?
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.
You may use the
# type: ignore[some-mypy-code,unused-ignore]
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:
try:
import graphlib # type: ignore[import,unused-ignore]
except ImportError:
pass
In the above, the ignore[import] ignores the import error (on Python 3.7 for example, where graphlib does not exist) and ignore[unused-ignore] ignores the error caused by the warn_unused_ignores mypy setting on e.g. Python 3.9 where this module is available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With