Fix false negative with walrus operator in tuples #20620
Closed
+137
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix false negative with walrus operator in tuples
Summary
Fixes #20606.
This PR fixes a regression introduced in mypy 1.18+ where type errors involving assignment expressions (walrus operators) inside tuples were silently ignored. In short: errors that should have been reported were not, resulting in false negatives.
Problem Description
Since commit
a856e55(#19767), mypy fails to detect certain type errors when assignment expressions appear inside tuples.The issue originates in
infer_context_dependent()insidechecker.py. This method uses an optimization where type inference is attempted twice:When walrus expressions are involved, the empty-context fallback can incorrectly infer types, effectively masking real errors.
Example
Expected
None + int)Actual
Why this happens
In the expression
(i := i + 1), when inferred without the tuple context, mypy infersiasintinstead ofint | None. That makes the expression appear valid, even though it isn’t.Root Cause
The empty-context fallback in
infer_context_dependent()is unsafe for expressions that contain assignment expressions.While the first inference pass correctly detects errors, the second pass can override those results with an incorrect but “valid-looking” inference.
Solution
This PR introduces a conservative fix:
contains_assignment_expr()that recursively checks whether an expression contains a walrus operator.infer_context_dependent().This preserves correctness without affecting the existing optimization for regular expressions.
Changes
infer_context_dependent()to skip empty-context inference when assignment expressions are presentcontains_assignment_expr()helper that handles all expression typesvisit_return_stmt()to includeAssignmentExprin the set of expression types checked in return valuesTesting
Test Cases
Before the fix
fn3()produced errorsAfter the fix
Additional Notes
a856e55)Files Changed
mypy/checker.pyinfer_context_dependent()visit_return_stmt()contains_assignment_expr()helper