python / python/mypy

Generics is not supported with some operators

Offen
#6,157 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug priority-1-normal topic-type-variables topic-union-types
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

  • Are you reporting a bug, or opening a feature request?
    Bug
  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.

Supporting operators with union does not work with generics.

S = TypeVar('S', bound=Union[int, float])
T = TypeVar('T', bound=Union[int, float])

def some_function(a:S, b:T) -> S:
    // do some operation and returns the type based on first parameter.
     c = a + b
    // if there is an addition involved in the computation, then we would get the below error. 
    // some_computed_variable would be finally computed and has the value based on first parameter type.
    return some_computed_variable

  • What is the actual behavior/output?
    error: Unsupported operand types for + ("S" and "T")

    We can use alias (Union[int, float] as type) instead of generics (S) as a workaround but it loses generic support.

  • What is the behavior/output you expect?
    Should not report error

  • What are the versions of mypy and Python you are using?
    Python: 3.6 mypy: 0.650

  • What are the mypy flags you are using? (For example --strict-optional)
    --ignore-missing-imports

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 damit, den generischen Operatorfall aus dem Issue mit einem aktuellen mypy-Checkout zu reproduzieren, und sieh dir anschließend die Änderung supporting-operators-with-union in PR #5545 an. Verfolge, wie gebundene Typvariablen bei der Addition geprüft werden, und füge Tests hinzu, die zeigen, dass kompatible generische Operanden akzeptiert werden, ohne den auf dem ersten Parameter basierenden Rückgabetyp zu verlieren.

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
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

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