Skip to content

Commit cc10d51

Browse files
Prefer the reflected operator method only when the operand types differ
check_op_reversible gave the reflected method priority whenever covers_at_runtime(right, left) held, but that also holds for equal operand types -- and the data model gives the reflected method priority only if the operands are of different types. For a < b with a and b of the same class where __lt__ and __gt__ are defined in different classes of the MRO, mypy inferred the result type of the reflected method that CPython never calls first. Fixes #22386.
1 parent 55472c0 commit cc10d51

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

‎mypy/checkexpr.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4326,8 +4326,17 @@ def check_op_reversible(
43264326
)
43274327
)
43284328
)
4329-
# Note: use `covers_at_runtime` instead of `is_subtype` (#19006)
4329+
# The reflected method goes first only when the right operand's
4330+
# type is a runtime subclass of the left's that is NOT the same
4331+
# type (the data model gives the reflected method priority only
4332+
# "if the operands are of different types"). covers_at_runtime
4333+
# rather than is_subtype kept in #19006 for `tuple[int, ...]` vs.
4334+
# a named subclass, where is_subtype failed on the tuple items;
4335+
# it also holds for equal types, which wrongly put the reflected
4336+
# method first when the operands have the same type but define
4337+
# __op__ and __rop__ in different classes of the MRO (#22386).
43304338
and covers_at_runtime(right_type, left_type)
4339+
and not is_same_type(left_type, right_type)
43314340
):
43324341
# When we do "A() + B()" where B is a subclass of A, we'll actually try calling
43334342
# B's __radd__ method first, but ONLY if B explicitly defines or overrides the

‎test-data/unit/check-expressions.test‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,25 @@ assert_type(tupX + size, Size)
704704

705705
[builtins fixtures/tuple-typeshed.pyi]
706706

707+
[case testReverseBinaryOperatorSameTypeDoesNotGetPriority]
708+
# The reflected method has priority only for operands of different types;
709+
# for same-type operands CPython calls the left's method first even when
710+
# __op__ and __rop__ are defined in different classes of the MRO (#22386).
711+
from typing import assert_type
712+
713+
class Base:
714+
def __lt__(self, other: "Base") -> str: return "lt"
715+
716+
class Child(Base):
717+
def __gt__(self, other: "Child") -> int: return 7
718+
719+
a = Child()
720+
b = Child()
721+
assert_type(a < b, str)
722+
assert_type(a > b, int)
723+
724+
[builtins fixtures/primitives.pyi]
725+
707726
[case testBinaryOperatorWithAnyRightOperand]
708727
from typing import Any, cast
709728
class A: pass

0 commit comments

Comments
 (0)