Skip to content

Commit 9681b26

Browse files
committed
Use isinstance information when type checking 'or' expressions
Note: This is not the same as python#942. It does address a pattern which occurs at least once in mypy itself though: ``` if res and (not isinstance(res, Instance) or cast(Instance, res).args): ```
1 parent 838b4e0 commit 9681b26

2 files changed

Lines changed: 14 additions & 5 deletions

File tree

‎mypy/checkexpr.py‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,16 +1078,19 @@ def check_boolean_op(self, e: OpExpr, context: Context) -> Type:
10781078
left_type = self.accept(e.left, ctx)
10791079

10801080
if e.op == 'and':
1081-
# else_map unused
1082-
if_map, else_map = \
1081+
right_map, _ = \
1082+
mypy.checker.find_isinstance_check(e.left, self.chk.type_map,
1083+
self.chk.typing_mode_weak())
1084+
elif e.op == 'or':
1085+
_, right_map = \
10831086
mypy.checker.find_isinstance_check(e.left, self.chk.type_map,
10841087
self.chk.typing_mode_weak())
10851088
else:
1086-
if_map = None
1089+
right_map = None
10871090

10881091
self.chk.binder.push_frame()
1089-
if if_map:
1090-
for var, type in if_map.items():
1092+
if right_map:
1093+
for var, type in right_map.items():
10911094
self.chk.binder.push(var, type)
10921095

10931096
right_type = self.accept(e.right, left_type)

‎test-data/unit/check-isinstance.test‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,12 @@ x = B() # type: A
731731

732732
if isinstance(x, B) and x.flag:
733733
pass
734+
if isinstance(x, B) or x.flag: # E: "A" has no attribute "flag"
735+
pass
736+
if not isinstance(x, B) or x.flag:
737+
pass
738+
if not isinstance(x, B) and x.flag: # E: "A" has no attribute "flag"
739+
pass
734740
[builtins fixtures/isinstancelist.py]
735741
[case testIsinstanceExpression]
736742
class A:

0 commit comments

Comments
 (0)