python / python/mypy

MyPy checks fail when overriding __eq__ to return a custom type and calling it as a right-operator

Open
#5,951 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-runtime-semantics
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

When I override __eq__ and return a custom type, the MyPy checks succeed when my custom type is on the LHS of the equality, but fail when my custom type is on the RHS of the equality.

Here is an example to illustrate: line 14 yields no error but line 16 yields an error:

Incompatible types in assignment (expression has type "bool", variable has type "MyClass")

from typing import Any


class MyClass:

    def __eq__(self, other: Any) -> 'MyClass':
        return self


def test_tmp() -> None:
    x = MyClass()
    y = 1.
    result: MyClass
    result = (x == y)
    assert type(result) == MyClass
    result = (y == x)
    assert type(result) == MyClass

The test passes, i.e. I get back an object of type MyClass when x is on the LHS or RHS of my equality.

NB - there is also a MyPy error on line 6, Return type of "__eq__" incompatible with supertype "object" - this is because of https://github.com/python/mypy/issues/2783. I think my issue is separate from this one.

Version numbers: Python 3.6.5, mypy 0.641.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided Python snippet with mypy and compare the inferred types for x == y and y == x. Investigate the equality operator handling that produces bool on the right-hand case; done means the assignment to result: MyClass is accepted consistently, while the separate __eq__ supertype error remains distinct.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.