From 4651e8507500d497419c36c9a97bd0fe146ea1c2 Mon Sep 17 00:00:00 2001 From: zhengdaodeguL <1159957339@qq.com> Date: Tue, 17 Nov 2026 17:58:52 +0000 Subject: [PATCH] Prefer reflected operator method only when operand types differ 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: #19006 relies on it for tuple[int, ...] vs a named tuple subclass. Add the different-types condition the data model requires. Fixes #22386 --- mypy/checkexpr.py | 3 +++ test-data/unit/check-expressions.test | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index c48f3da51f85e..63e575a0ed3e7 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4413,7 +4413,10 @@ def check_op_reversible( ) ) ) + # The data model gives reflected methods priority only for proper subclasses, + # not same-type operands (#22386). # Note: use `covers_at_runtime` instead of `is_subtype` (#19006) + and not is_same_type(left_type, right_type) and covers_at_runtime(right_type, left_type) ): # When we do "A() + B()" where B is a subclass of A, we'll actually try calling diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index 1bd955b6b7329..7cf03c4e33983 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -704,6 +704,23 @@ assert_type(tupX + size, Size) [builtins fixtures/tuple-typeshed.pyi] +[case testReverseBinaryOperatorSameTypeDoesNotGetPriority] +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 + +class Sub(Child): pass + +a = Child() +b = Child() +assert_type(a < b, str) +assert_type(a > b, int) +assert_type(a < Sub(), int) + [case testBinaryOperatorWithAnyRightOperand] from typing import Any, cast class A: pass