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

mypy does not recognize sys.platform with ternary operator #13003

Open
amatyukhin0 opened this issue Jun 21, 2022 · 2 comments
Open

mypy does not recognize sys.platform with ternary operator #13003

amatyukhin0 opened this issue Jun 21, 2022 · 2 comments

Comments

@amatyukhin0
Copy link

Bug Report

mypy can recognize sys.platform in if cond: ... / else: ... conditions but fails to do it if ternary operator (a if cond else b) is used.

To Reproduce

Consider this piece of code, assuming we are on Linux:

import signal
import sys

signal_type = signal.SIGBREAK if sys.platform == 'win32' else signal.SIGTERM

Expected Behavior

mypy should not raise any error.

Actual Behavior

mypy fails with:

main.py:4: error: Module has no attribute "SIGBREAK"
Found 1 error in 1 file (checked 1 source file)

Environment

  • Mypy version used: 0.961
  • Python version used: 3.10
  • Operating system: Linux
@amatyukhin0 amatyukhin0 added the bug mypy got something wrong label Jun 21, 2022
@AlexWaygood
Copy link
Member

I think this is better classified as a feature rather than a bug, since PEP 484 states:

Type checkers are expected to understand simple version and platform checks

(Emphasis mine on "simple".)

@jaraco
Copy link
Member

jaraco commented Aug 29, 2024

I'd argue a ternary expression is more simple than if/else blocks:

  • A ternary expression has exactly one assignment, so there's less ambiguity around the effect of the conditional. One variable gets assigned unconditionally or not at all.
  • It's not possible to interleave other concerns, such as assigning other variables.
  • It's not possible to have arbitrary side-effects in either logical branch (e.g. sys.path.insert()).

These are the same reasons that I encourage use of the ternary expression, as these constraints also help protect the logical safety of the operation.

</soapbox>

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

3 participants