Skip to content

Fix loss of type inference in chained comparisons#21159

Closed
aryanjsingh wants to merge 1 commit intopython:masterfrom
aryanjsingh:fix/issue-21149-120-regression-loss-of-type-inference-of
Closed

Fix loss of type inference in chained comparisons#21159
aryanjsingh wants to merge 1 commit intopython:masterfrom
aryanjsingh:fix/issue-21149-120-regression-loss-of-type-inference-of

Conversation

@aryanjsingh
Copy link
Copy Markdown

Summary

A regression in mypy 1.20 caused loss of type narrowing for operands in chained comparisons. This was due to an overly aggressive check in the type binder that prevented unwanted type widening but also discarded valid narrowing from expressions like is not. The fix refines this check to distinguish between merging control-flow branches and sequential updates within an expression, ensuring that narrowing is preserved in chained comparisons.

Changes

  • mypy/binder.py: In mypy/binder.py, the update_from_options method has been modified to correctly handle type narrowing in chained comparisons. The original logic was too aggressive in preventing type widening and inadvertently discarded valid narrowing. The fix introduces a check on the number of frames being merged: if only one frame is involved, it's treated as a sequential update (like in a chained comparison) and the type narrowing is allowed to proceed. This restores correct type inference without re-introducing the bug the original code was intended to fix.

Related Issue

Closes #21149

A regression was introduced that caused loss of type inference for operands in chained comparisons, such as `None is not a == b`. The logic to prevent unwanted type widening was too aggressive and discarded valid narrowing from `is not` checks.

The fix adjusts the condition in `update_from_options` to allow updates when only a single frame is being merged. This correctly identifies sequential updates within expressions (like chained comparisons) and preserves the narrowing, while still preventing unwanted widening when merging multiple control-flow branches.
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 3, 2026

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@hauntsaninja
Copy link
Copy Markdown
Collaborator

Thanks, but this issue is already fixed on master. I also don't really understand this proposed fix. PRs to mypy should come with tests.

@aryanjsingh aryanjsingh deleted the fix/issue-21149-120-regression-loss-of-type-inference-of branch April 4, 2026 00:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[1.20 regression] loss of type inference of chained-comparison operands

2 participants