Skip to content

Commit

Permalink
Consider reversed operands order when comparing version info (#10288)
Browse files Browse the repository at this point in the history
Closes #10264.

Consider reversed order of operands when trying to compare version info. When reversed order is used, operator is reversed as well for correct comparison.
  • Loading branch information
kamilturek authored Apr 8, 2021
1 parent ee05821 commit 1567e36
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
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

0 comments on commit 1567e36

Please sign in to comment.