@@ -4767,8 +4767,12 @@ def infer_rvalue_with_fallback_context(
47674767 # binder.accumulate_type_assignments() and assign the types inferred for type
47684768 # context that is ultimately used. This is however tricky with redefinitions.
47694769 # For now we simply disable second accept in cases known to cause problems,
4770- # see e.g. testAssignToOptionalTupleWalrus.
4771- has_walrus = self ._has_assignment_expr (rvalue )
4770+ # see e.g. testAssignToOptionalTupleWalrus. We only need to scan for walrus
4771+ # when union fallback is otherwise applicable.
4772+ union_fallback_possible = (
4773+ preferred_context is not None and isinstance (get_proper_type (lvalue_type ), UnionType )
4774+ )
4775+ has_walrus = union_fallback_possible and self ._has_assignment_expr (rvalue )
47724776
47734777 fallback_context_used = False
47744778 with (
@@ -4795,11 +4799,7 @@ def infer_rvalue_with_fallback_context(
47954799 # Try re-inferring r.h.s. in empty context for union with explicit annotation,
47964800 # and use it results in a narrower type. This helps with various practical
47974801 # examples, see e.g. testOptionalTypeNarrowedByGenericCall.
4798- union_fallback = (
4799- preferred_context is not None
4800- and isinstance (get_proper_type (lvalue_type ), UnionType )
4801- and not has_walrus
4802- )
4802+ union_fallback = union_fallback_possible and not has_walrus
48034803
48044804 # Skip literal types, as they have special logic (for better errors).
48054805 try_fallback = redefinition_fallback or union_fallback or argument_redefinition_fallback
0 commit comments