Skip to content

Commit be66d9d

Browse files
committed
Use union of current context and left side for right side narrowing
1 parent 325f776 commit be66d9d

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

mypy/checkexpr.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5879,16 +5879,20 @@ def analyze_cond_branch(
58795879
allow_none_return: bool = False,
58805880
suppress_unreachable_errors: bool = True,
58815881
) -> Type:
5882+
if self.type_context and self.type_context[-1] is not None:
5883+
ctx = make_simplified_union([context, self.type_context[-1]])
5884+
else:
5885+
ctx = context
58825886
with self.chk.binder.frame_context(can_skip=True, fall_through=0):
58835887
if map is None:
58845888
# We still need to type check node, in case we want to
58855889
# process it for isinstance checks later. Since the branch was
58865890
# determined to be unreachable, any errors should be suppressed.
58875891
with self.msg.filter_errors(filter_errors=suppress_unreachable_errors):
5888-
self.accept(node, type_context=context, allow_none_return=allow_none_return)
5892+
self.accept(node, type_context=ctx, allow_none_return=allow_none_return)
58895893
return UninhabitedType()
58905894
self.chk.push_type_map(map)
5891-
return self.accept(node, type_context=context, allow_none_return=allow_none_return)
5895+
return self.accept(node, type_context=ctx, allow_none_return=allow_none_return)
58925896

58935897
#
58945898
# Helpers

test-data/unit/check-inference-context.test

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1510,3 +1510,24 @@ def mymin(
15101510
def check(paths: Iterable[str], key: Callable[[str], int]) -> Union[str, None]:
15111511
return mymin(paths, key=key, default=None)
15121512
[builtins fixtures/tuple.pyi]
1513+
1514+
[case testBinaryOpInferenceContext]
1515+
from typing import Literal, TypeVar
1516+
1517+
T = TypeVar("T")
1518+
1519+
def identity(x: T) -> T:
1520+
return x
1521+
1522+
def check1(use: bool, val: str) -> "str | Literal[True]":
1523+
return use or identity(val)
1524+
1525+
def check2(use: bool, val: str) -> "str | bool":
1526+
return use or identity(val)
1527+
1528+
def check3(use: bool, val: str) -> "str | Literal[False]":
1529+
return use and identity(val)
1530+
1531+
def check4(use: bool, val: str) -> "str | bool":
1532+
return use and identity(val)
1533+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)