python / python/mypy

Type of argument is not inferred for a TypeVar in a Generic type

Offen
#5,324 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

documentation priority-1-normal topic-type-variables topic-usability
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Mypy needs a type annotation for a variable that it could easily infer from the constructor argument annotations. This works perfectly with normal types. But using a TypeVar in a Generic type, somehow it doesn't.

from typing import Generic, TypeVar


class A:
    pass


class B:
    pass


T_Value = TypeVar("T_Value", A, B)


class Guess(Generic[T_Value]):
    def __init__(self, value: T_Value, confidence: float) -> None:
        self.value = value  # <-- line 17
        self.confidence = confidence

Mypy then complains it needs a type annotation

foo.py:17: error: Need type annotation for 'value'

This of course is no big deal since I can just add that annotation:

class Guess(Generic[T_Value]):
    def __init__(self, value: T_Value, confidence: float) -> None:
        self.value: T_Value = value
        self.confidence = confidence

But shouldn't mypy infer the type from the type annotations in the constructor?

If I'm doing something wrong please let me now.
I didn't find a similar issue but if this is a duplicate feel free to close.

I'm using:
Python 3.7.0, mypy 0.610, macOS 10.13.5

Same result with the current master (2018-07-05):
mypy 0.620+dev-f5058bcb269a55b33a02c3e3fd345541839bf06e

Flags I'm using:
strict_optional = true
ignore_missing_imports = true
follow_imports = silent

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

Reproduziere das Inline-Python-Beispiel mit den gemeldeten Einstellungen für strict_optional, ignore_missing_imports und follow_imports. Beginne damit, mypy's Inferenz für die Zuweisung des Generic TypeVar-Attributs nachzuverfolgen; abgeschlossen ist die Aufgabe, wenn das Beispiel keine explizite Annotation mehr erfordert und das Verhalten durch einen Regressionstest abgedeckt ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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