Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,11 @@ def __init__(
self._unique_id = 0
self._variance_dummy_type = None

# Assignment expression is the only *expression* that can have externally
# visible effects via binder. We bump this whenever this happens to handle
# situations when some expressions are accepted multiple times.
self.assignment_expression_effect = 0

@property
def expr_checker(self) -> mypy.checkexpr.ExpressionChecker:
return self._expr_checker
Expand Down Expand Up @@ -4772,7 +4777,7 @@ def infer_rvalue_with_fallback_context(
# context that is ultimately used. This is however tricky with redefinitions.
# For now we simply disable second accept in cases known to cause problems,
# see e.g. testAssignToOptionalTupleWalrus.
binder_version = self.binder.version
assignment_expression_effect = self.assignment_expression_effect

fallback_context_used = False
with (
Expand Down Expand Up @@ -4802,7 +4807,7 @@ def infer_rvalue_with_fallback_context(
union_fallback = (
preferred_context is not None
and isinstance(get_proper_type(lvalue_type), UnionType)
and binder_version == self.binder.version
and assignment_expression_effect == self.assignment_expression_effect
)

# Skip literal types, as they have special logic (for better errors).
Expand Down
3 changes: 3 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -4461,7 +4461,10 @@ def check_list_multiply(self, e: OpExpr) -> Type:

def visit_assignment_expr(self, e: AssignmentExpr) -> Type:
value = self.accept(e.value)
binder_version = self.chk.binder.version
self.chk.check_assignment(e.target, e.value)
if self.chk.binder.version != binder_version:
self.chk.assignment_expression_effect += 1
self.chk.check_final(e)
if not has_uninhabited_component(value):
# TODO: can we get rid of this extra store_type()?
Expand Down
13 changes: 13 additions & 0 deletions test-data/unit/check-inference-context.test
Original file line number Diff line number Diff line change
Expand Up @@ -1616,3 +1616,16 @@ async def outer(c: Cls[T]) -> Optional[T]:
return await inner(c)
[builtins fixtures/async_await.pyi]
[typing fixtures/typing-async.pyi]

[case testContextFallbackNarrowingTernaryRValue]
from typing import Iterable, Union

def foo(args: Union[Iterable[Union[str, int]], str, int]) -> Iterable[str]:
if isinstance(args, (str, int)):
args = (args,)
args = (
arg if isinstance(arg, str) else str()
for arg in args
)
return args
[builtins fixtures/isinstancelist.pyi]
Loading