Skip to content

comparison of two operands of the same type calls the reflected method first when __lt__ and __gt__ are defined in different classes #22386

Open

Description

@DerekLaymn

Bug Report

For a < b where a and b have exactly the same type, CPython calls a.__lt__(b). The reflected method b.__gt__(a) goes first only if the type of b is a proper subclass of the type of a (data model, object.__lt__: "If the operands are of different types, and the right operand's type is a direct or indirect subclass of the left operand's type, the reflected method of the right operand has priority"). mypy tries b.__gt__(a) first for operands of the same type when __lt__ and __gt__ are defined in different classes of the MRO, so it infers the result type of the wrong method.

To Reproduce

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()
s: str = a < b
assert_type(a < b, str)
assert_type(a > b, int)
print(repr(a < b), repr(a > b))

Actual Behavior

$ mypy --python-version 3.13 --no-incremental test_bug.py
test_bug.py:16: error: Incompatible types in assignment (expression has type "int", variable has type "str")  [assignment]
test_bug.py:17: error: Expression is of type "int", not "str"  [assert-type]
test_bug.py:18: error: Expression is of type "str", not "int"  [assert-type]
Found 3 errors in 1 file (checked 1 source file)

$ python test_bug.py
'lt' 7

Expected Behavior

No errors: a < b is str and a > b is int. pyright 1.1.414 and ty 0.0.97 report nothing for this file.

What I tried:

  • <= in Base and >= in Child: same swap.
  • Both methods in one class: correct. The swap needs the two methods to come from different classes.
  • __add__ in Base and __radd__ in Child with two Child operands: correct, a + b is str (mypy reports the unsafe overlap of the two methods on the class, which is a separate message).
  • The right operand of a proper subclass of Child (a <= c with class Sub(Child)): mypy infers int, which is also what CPython returns, because Sub is a proper subclass.

Cause, as far as I can tell from check_op_reversible in checkexpr.py on master: the branch for two operands of the same type is guarded by op_name in operators.op_methods_that_shortcut, and that set holds the arithmetic and bitwise methods (__add__ to __rshift__) but no comparison. For < mypy therefore goes to the next branch, which puts the reflected method first when lookup_definer(left_type, "__lt__") != lookup_definer(right_type, "__gt__") and covers_at_runtime(right_type, left_type) holds. It does not check that the two types differ.

My Environment

  • Mypy version used: 2.4.0, 2.4.1 and master 2.5.0+dev.879da562
  • Mypy command-line flags: --python-version 3.13 --no-incremental
  • Python version used: 3.13.16
  • OS: Linux

Playground

Activity

  1. hamarshehmhmd commented on Nov 6, 2026

    @hamarshehmhmd

    Nice write-up — I hit the same thing with your repro on current master.

    Root cause: as you traced in check_op_reversible, the same-type shortcut only applies when op_name in operators.op_methods_that_shortcut. That set has the arithmetic/bitwise methods but not the comparisons, so for < mypy falls into the next branch and prefers the reflected method whenever lookup_definer(left, "__lt__") != lookup_definer(right, "__gt__") and covers_at_runtime holds — which is true for two Child instances even though the types are identical. CPython only gives the reflected method priority for a proper subclass on the right.

    Fix in mypy/operators.py — extend the shortcut set:

    op_methods_that_shortcut: Final = {
        "__add__",
        "__sub__",
        # ... existing arithmetic/bitwise ...
        "__lshift__",
        "__rshift__",
        # Comparisons also short-circuit on identical operand types (data model for
        # object.__lt__: reflected method only gets priority for a proper subclass).
        "__lt__",
        "__le__",
        "__gt__",
        "__ge__",
    }

    When the types differ and the RHS is a proper subclass, is_same_type is false, so the existing covers_at_runtime branch still prefers the reflected method — matching CPython.

    Verified:

    • Your repro: mypy --python-version 3.13 --no-incremental → Success: no issues found; runtime prints 'lt' 7
    • Subclass case (a < Sub()): still inferred as int, matching CPython
    • Added testSameTypeComparisonPrefersForwardMethod to test-data/unit/check-expressions.test
    • pytest -q mypy/test/testcheck.py -k testSameTypeComparisonPrefersForwardMethod → 1 passed

    Happy to open a PR.

  2. zhengdaodeguL commented on Nov 17, 2026

    @zhengdaodeguL

    Fixed in #22507: the reflected-first shortcut in check_op_reversible no longer applies when both operands have the same type, so a < b now infers the return type of a.__lt__ as CPython does. The narrower fix keeps covers_at_runtime and is line-for-line equivalent to #22391, whose mypy_primer run showed zero impact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions