Skip to content

Commit c106579

Browse files
rowilliagvanrossum
authored andcommitted
Suppress any errors found in a boolean expression after filtering out all possible types. (#3666)
This fixes #3643
1 parent f127e2c commit c106579

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

mypy/checkexpr.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -1519,7 +1519,16 @@ def check_boolean_op(self, e: OpExpr, context: Context) -> Type:
15191519
elif e.right_always:
15201520
left_map = None
15211521

1522-
right_type = self.analyze_cond_branch(right_map, e.right, left_type)
1522+
# If right_map is None then we know mypy considers the right branch
1523+
# to be unreachable and therefore any errors found in the right branch
1524+
# should be suppressed.
1525+
if right_map is None:
1526+
self.msg.disable_errors()
1527+
try:
1528+
right_type = self.analyze_cond_branch(right_map, e.right, left_type)
1529+
finally:
1530+
if right_map is None:
1531+
self.msg.enable_errors()
15231532

15241533
if right_map is None:
15251534
# The boolean expression is statically known to be the left value

test-data/unit/check-isinstance.test

+2
Original file line numberDiff line numberDiff line change
@@ -1187,6 +1187,8 @@ if isinstance(x, B) and isinstance(y, int):
11871187
1() # type checking skipped
11881188
if isinstance(y, int) and isinstance(x, B):
11891189
1() # type checking skipped
1190+
if isinstance(y, int) and y > 42:
1191+
1() # type checking skipped
11901192
[builtins fixtures/isinstancelist.pyi]
11911193

11921194
[case testReturnWithCallExprAndIsinstance]

test-data/unit/check-optional.test

+15
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,21 @@ if x is not None:
548548

549549
[builtins fixtures/ops.pyi]
550550

551+
[case testOptionalTypeNarrowedInBooleanStatement]
552+
from typing import Optional
553+
554+
x: Optional[int] = None
555+
x is not None and x + 42
556+
x is not None and x + '42' # E: Unsupported operand types for + ("int" and "str")
557+
[builtins fixtures/isinstance.pyi]
558+
559+
[case testInvalidBooleanBranchIgnored]
560+
from typing import Optional
561+
562+
x = None
563+
x is not None and x + 42
564+
[builtins fixtures/isinstance.pyi]
565+
551566
[case testOptionalLambdaInference]
552567
from typing import Optional, Callable
553568
f = None # type: Optional[Callable[[int], None]]

0 commit comments

Comments
 (0)