Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading