python / python/mypy

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

Offen
#5,951 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-runtime-semantics
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Führe zunächst das bereitgestellte Python-Snippet mit mypy aus und vergleiche die abgeleiteten Typen für x == y und y == x. Untersuche die Behandlung des Gleichheitsoperators, die im Fall der rechten Seite bool erzeugt; fertig ist es, wenn die Zuweisung zu result: MyClass konsistent akzeptiert wird, während der separate __eq__-Supertypfehler davon getrennt bleibt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.