You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Use of sys.version_info in ternary operator with straddling code is not handled correctly #5550
When if statements are used, mypy is able to recognize the use of the sys.version_info and handle the types correctly for straddling code that needs to work with both Python 3 and 2. Unfortunately, mypy is not able to handle the same case with a ternary operator.
# using mypy --python-version 3.7 /path/to/file
...: error: "bytes" has no attribute "encode"; maybe "decode"?
# using mypy --python-version 2.7 /path/to/file
...: error: Incompatible return value type (got "unicode", expected "str")
When the same function is changed into this:
def ensure_native_str(str_or_bytes): # type: (Union[Text, bytes]) -> str
if isinstance(str_or_bytes, str):
return str_or_bytes
if six.PY3:
return str_or_bytes.decode('utf-8')
return str_or_bytes.encode('utf-8')
it passes mypy checks with both --python-version 3.7 and --python-version 2.7.
This means that the branches in straddling code were correctly handled and the types inferred appropriately. With the ternary operator above, unfortunately, that did not happen.
This was tested with both mypy-0.620 and mypy-0.560.
Python version that mypy was run with was 3.6.
When six.PY3 is replaced with the explicit sys.version_info[0] == 3 the behavior is the same.
The if statement version passes the checks, the ternary operator version doesn't.
Activity
ilevkivskyi commentedon Sep 1, 2018
PEP 484 specifies which forms of version an platform checks should be supported by type checkers, see https://www.python.org/dev/peps/pep-0484/#version-and-platform-checking. And ternary expressions are not there.
Anyway, this one looks like relatively straightforward to implement so I think we can keep this open.
hauntsaninja commentedon Aug 28, 2023
Python 2 is very dead