Skip to content

Consider reversed operands order when comparing version info #10288

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

Merged
merged 4 commits into from
Apr 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions mypy/reachability.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@
MYPY_FALSE: MYPY_TRUE,
} # type: Final

reverse_op = {"==": "==",
"!=": "!=",
"<": ">",
">": "<",
"<=": ">=",
">=": "<=",
} # type: Final


def infer_reachability_of_if_statement(s: IfStmt, options: Options) -> None:
for i in range(len(s.expr)):
Expand Down Expand Up @@ -127,10 +135,13 @@ def consider_sys_version_info(expr: Expression, pyversion: Tuple[int, ...]) -> i
op = expr.operators[0]
if op not in ('==', '!=', '<=', '>=', '<', '>'):
return TRUTH_VALUE_UNKNOWN
thing = contains_int_or_tuple_of_ints(expr.operands[1])
if thing is None:
return TRUTH_VALUE_UNKNOWN

index = contains_sys_version_info(expr.operands[0])
thing = contains_int_or_tuple_of_ints(expr.operands[1])
if index is None or thing is None:
index = contains_sys_version_info(expr.operands[1])
thing = contains_int_or_tuple_of_ints(expr.operands[0])
op = reverse_op[op]
if isinstance(index, int) and isinstance(thing, int):
# sys.version_info[i] <compare_op> k
if 0 <= index <= 1:
Expand Down
10 changes: 10 additions & 0 deletions test-data/unit/check-unreachable-code.test
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,16 @@ reveal_type(foo()) # N: Revealed type is 'builtins.str'
[builtins_py2 fixtures/ops.pyi]
[out]

[case testSysVersionInfoReversedOperandsOrder]
import sys
if (3,) <= sys.version_info:
def foo() -> int: return 0
else:
def foo() -> str: return ''
reveal_type(foo()) # N: Revealed type is "builtins.int"
[builtins fixtures/ops.pyi]
[out]

[case testSysVersionInfoNegated]
import sys
if not (sys.version_info[0] < 3):
Expand Down