Skip to content

fix: do not narrow expression type to TypeVar on equality comparison#21209

Open
ordinary9843 wants to merge 1 commit intopython:masterfrom
ordinary9843:fix/typevar-equality-narrowing
Open

fix: do not narrow expression type to TypeVar on equality comparison#21209
ordinary9843 wants to merge 1 commit intopython:masterfrom
ordinary9843:fix/typevar-equality-narrowing

Conversation

@ordinary9843
Copy link
Copy Markdown

When a variable is compared with == against a TypeVar operand, mypy was narrowing the left-hand variable to the TypeVar type. This caused false errors on subsequent operations — for example, x: int would be narrowed to T after assert x == y (where y: T), causing x += 1 to be flagged as unsupported operands.

The regression was introduced in #20602, which routed == through narrow_type_by_identity_equality but did not guard against TypeVar targets. A TypeVar represents an unknown concrete type at the call site, so narrowing based on it can only lose information, not gain it.

This fix skips narrowing in narrow_type_by_identity_equality when the target type is a TypeVarLikeType. A more precise approach — intersecting the expression type with the TypeVar's upper bound — would require intersection type support and can be done as a follow-up.

Fixes #21199

@ordinary9843 ordinary9843 force-pushed the fix/typevar-equality-narrowing branch from dc409ce to ff07d6d Compare April 13, 2026 07:48
@github-actions
Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

zulip (https://github.com/zulip/zulip)
- zerver/lib/validator.py:331: error: Redundant cast to "ResultT"  [redundant-cast]

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] Too aggressive type narrowing with type variables and equality

1 participant