Skip to content

Do not prefer the reflected operator method for same-type operands - #22507

Open
zhengdaodeguL wants to merge 1 commit into
python:masterfrom
zhengdaodeguL:fix/same-type-comparison-22386
Open

zhengdaodeguL wants to merge 1 commit into
python:masterfrom
zhengdaodeguL:fix/same-type-comparison-22386

Conversation

@zhengdaodeguL

Copy link
Copy Markdown

Fixes #22386

For a < b where a and b have exactly the same type, CPython calls a.__lt__(b); the reflected method b.__gt__(a) only takes priority when the type of b is a proper subclass of the type of a. mypy tried the reflected method first whenever __lt__ and __gt__ were defined in different classes of the MRO, inferring the wrong method return type.

This narrows the reflected-first shortcut in check_op_reversible so it does not apply when the operand types are the same (covers_at_runtime is kept, since #19006 relies on it). The broader fix in #22402 (adding the operators to op_methods_that_shortcut) introduced false positives in mypy_primer (apache/spark, pandas); this narrower change is line-for-line equivalent to #22391, whose mypy_primer run showed zero impact on open-source code.

Tests: new testReverseBinaryOperatorSameTypeDoesNotGetPriority in check-expressions.test (issue repro plus a true-subclass case that still prefers the reflected method). pytest mypy/test/testcheck.py -k "check-expressions or check-operator": 203 passed.

CPython gives the reflected method of the right operand priority only
if the operands are of different types and the right operand's type
is a subclass of the left's. check_op_reversible gave it priority
whenever covers_at_runtime(right_type, left_type) held, but that
predicate is also true for equal operand types, so for same-type
operands with __lt__ and __gt__ defined in different classes of the
MRO mypy inferred the result type of the wrong method.

Keep covers_at_runtime rather than is_subtype: python#19006 relies on it
for tuple[int, ...] vs a named tuple subclass. Add the different-types
condition the data model requires.

Fixes python#22386
@github-actions

Copy link
Copy Markdown
Contributor

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

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.

comparison of two operands of the same type calls the reflected method first when __lt__ and __gt__ are defined in different classes

1 participant