Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Respect sys.platform platform check assertion inside functions #9025

Open
nipunn1313 opened this issue Jun 19, 2020 · 2 comments
Open

Respect sys.platform platform check assertion inside functions #9025

nipunn1313 opened this issue Jun 19, 2020 · 2 comments

Comments

@nipunn1313
Copy link
Contributor

This is a feature request

From the docs
https://mypy.readthedocs.io/en/stable/common_issues.html#python-version-and-system-platform-checks

More specifically, mypy will understand the use of sys.version_info and sys.platform checks
within if/elif/else statements.

and

As a special case, you can also use one of these checks in a top-level (unindented) assert; this makes mypy skip the rest of the file.

It would be nice if this kind of code would also typecheck on mac/linux.
Currently the option is to refactor such that you can define the entire function within an if sys.platform == "win32"

class A:
   def func_on_win_only() -> str:
      assert sys.platform == "win32"
      return sys.getwindowsversion()
@AlexWaygood
Copy link
Member

I figured out a hacky workaround for this in #11909. Instead of having assert sys.platform == "win32" at the top of the function, instead do this:

if sys.platform != "win32":
    assert False

@ncoghlan
Copy link

ncoghlan commented Aug 27, 2024

Just noting that the assert False form also works when filtering out single code branches within a larger function using a library or application specific check. For example:

_WINDOWS_BUILD = hasattr(os, "add_dll_directory")

def some_function():
    if _WINDOWS_BUILD:
        if sys.platform != "win32":
            assert False
        # mypy allows Windows-only API usage here
    else:
        if sys.platform == "win32":
            assert False
        # mypy allows *nix-only API usage here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants