diff --git a/mypy/reachability.py b/mypy/reachability.py index 5ee813dc982c..0a29c9b3bba7 100644 --- a/mypy/reachability.py +++ b/mypy/reachability.py @@ -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)): @@ -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] k if 0 <= index <= 1: diff --git a/test-data/unit/check-unreachable-code.test b/test-data/unit/check-unreachable-code.test index 6772a74f5163..6f04f83af5ad 100644 --- a/test-data/unit/check-unreachable-code.test +++ b/test-data/unit/check-unreachable-code.test @@ -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):