python / python/mypy

__r<magic>__ methods for reflected (swapped) operands doesnt duck type int to float

Offen
#9,388 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

🐛 Bug Report

It seems like ints are not compatible with floats when used in the __r<magic>__ methods for reflected (swapped) operands like __radd__ the same was as in normal operands if the int/float is used as a type parameter in a generic type.

As a workaround it works if I specify a union type with the int case as well, but would be nice to not have to do that since its not needed otherwise.

To Reproduce

code.py:

from typing import List

class Vec:
    def __add__(self, other: List[float]) -> None:
        pass

    def __radd__(self, other: List[float]) -> None:
        pass

r1 = Vec() + [1]
r2 = [1] + Vec()  # error line
r3 = [1.0] + Vec()

Type checking the above code with python -m mypy code.py

Expected Behavior

I expect the r2 case to work as well

Actual Behavior

I get this error message for the r2 line: error: Unsupported operand types for + ("List[int]" and "Vec")

Your Environment

  • Mypy version used: 0.782
  • Mypy configuration options from mypy.ini (and other config files): No special config
  • Python version used: CPython 3.8.4, 32 bit.
  • Operating system and version: Windows 10

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

Beginne mit der Reproduktion des Issues in code.py und führe python -m mypy code.py mit den gemeldeten Fällen aus. Verfolge, wie die Operandenprüfung mit __add__ im Gegensatz zum reflektierten __radd__ umgeht, wenn List[int] mit List[float] verglichen wird; abgeschlossen ist die Aufgabe, wenn der Fall r2 eine Typprüfung ohne erforderlichen Union-Workaround besteht und die bestehenden Fälle weiterhin korrekt bleiben.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

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