Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 331
ChrisB Avatar asked Sep 29 '26 16:09

ChrisB


2 Answers

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.

like image 68
ChrisB Avatar answered Oct 02 '26 07:10

ChrisB


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.

like image 39
np8 Avatar answered Oct 02 '26 05:10

np8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!