python / python/mypy

Better error message for incompatible type assignment when using Generics

Offen
#8,934 9 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

diagnostics needs discussion priority-1-normal
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?

Feature Request

  • Please insert below the code you are checking with mypy.
from typing import Generic, TypeVar


T = TypeVar("T", int, float)


class Foo(Generic[T]):
    def __init__(self, val: T):
        self.data: T = val 


def bar(x: T) -> Foo[T]:
    return Foo(x)


x = bar(1)
x = bar(2.0) # error thrown by mypy
  • What is the actual behavior/output?
    mypy throws this error:
error: Argument 1 to "bar" has incompatible type "float"; expected "int"
  • What is the behavior/output you expect?

This error message is thrown because of the combination of assigning a different type to x and using Generic. The error message is unclear because it indicates a type error on the argument passed to bar and can be interpreted as bar not accepting arguments of type float.

Having a different error message that mentions "Incompatible types in assignment" would be clearer.
A message to make it clearer that expression has type Foo[float], variable has type Foo[int]

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

mypy 0.770 and Python 3.7.6

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

None

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, das Generic-Beispiel mit mypy 0.770 und Python 3.7.6 zu reproduzieren, wobei du dich auf die Zuweisung von Foo[int] zu Foo[float] konzentrierst. Verfolge die für den Aufruf von bar und die Zuweisung zu x erzeugte Diagnose; fertig ist die Aufgabe, wenn die Meldung die inkompatiblen Variablen- und Ausdruckstypen eindeutig identifiziert, statt anzudeuten, dass bar float-Argumente ablehnt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Feature
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.