From cc10d511d98201ce8e09db349ae3aa2d0d6daa34 Mon Sep 17 00:00:00 2001 From: Reza Mulia Wijaya <112234018+rezamuliawijaya@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:06:24 +0700 Subject: [PATCH] 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. --- mypy/checkexpr.py | 11 ++++++++++- test-data/unit/check-expressions.test | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index e0e10e8b890d8..8584ed1ec3f6b 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4326,8 +4326,17 @@ def check_op_reversible( ) ) ) - # Note: use `covers_at_runtime` instead of `is_subtype` (#19006) + # The reflected method goes first only when the right operand's + # type is a runtime subclass of the left's that is NOT the same + # type (the data model gives the reflected method priority only + # "if the operands are of different types"). covers_at_runtime + # rather than is_subtype kept in #19006 for `tuple[int, ...]` vs. + # a named subclass, where is_subtype failed on the tuple items; + # it also holds for equal types, which wrongly put the reflected + # method first when the operands have the same type but define + # __op__ and __rop__ in different classes of the MRO (#22386). and covers_at_runtime(right_type, left_type) + and not is_same_type(left_type, right_type) ): # When we do "A() + B()" where B is a subclass of A, we'll actually try calling # B's __radd__ method first, but ONLY if B explicitly defines or overrides the diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index 1bd955b6b7329..6662584b1f639 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -704,6 +704,25 @@ assert_type(tupX + size, Size) [builtins fixtures/tuple-typeshed.pyi] +[case testReverseBinaryOperatorSameTypeDoesNotGetPriority] +# The reflected method has priority only for operands of different types; +# for same-type operands CPython calls the left's method first even when +# __op__ and __rop__ are defined in different classes of the MRO (#22386). +from typing import assert_type + +class Base: + def __lt__(self, other: "Base") -> str: return "lt" + +class Child(Base): + def __gt__(self, other: "Child") -> int: return 7 + +a = Child() +b = Child() +assert_type(a < b, str) +assert_type(a > b, int) + +[builtins fixtures/primitives.pyi] + [case testBinaryOperatorWithAnyRightOperand] from typing import Any, cast class A: pass