pythonwindowscross-platformmypy

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

Is there any reasonable way to deal with this ? My current solution is

Are there any better solutions for this?


Solution

  • 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.