diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index c48f3da51f85..63e575a0ed3e 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 1bd955b6b732..7cf03c4e3398 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