python / python/mypy

Generic class clone method using property variable for type arg produces name-defined error

Offen
#17,302 0 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

My Python code is running fine for what I want it to do, but I've had to silence this mypy error in this case, where it does not appear to be correct. A property is used to access the __orig_class__ variable.

To reproduce:
mypy playground - https://mypy-play.net/?mypy=1.10.0&python=3.12&gist=063c6160fe6d1bf37973f47906a6d997

from __future__ import annotations
from typing import Generic, TypeVar, get_args

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

class Foo(Generic[T]):
    @property
    def t(self) -> type[T]:
        return get_args(self.__orig_class__)[0]  # Get the type arg, (int)
    
    def clone(self) -> Foo[T]:
        return Foo[self.t]()  # test.py:12: error: Name "self.t" is not defined  [name-defined]
    
    def no_complaint(self) -> None:
        print(self.t("1"))


foo = Foo[int]()
foo.no_complaint()  # `1`
r = foo.clone()
r.no_complaint()    # `1`

Expected behaviour
Mypy reports no errors, python code runs correctly.

Actual behaviour
Python code runs correctly.
Mypy returns
test.py:12: error: Name "self.t" is not defined [name-defined]

Environment
Base install with:
mypy==1.10.0
python==3.11.4

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 dem verknüpften mypy playground und dem gemeldeten Beispiel für Python 3.12 und mypy 1.10.0 in test.py. Verfolge anschließend, wie die name-defined-Diagnose für self.t innerhalb von Foo.clone erzeugt wird. Als erledigt gilt die Aufgabe, wenn die Reproduktion keine Fehler meldet und dabei das gezeigte Laufzeitverhalten beibehält.

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
45/100

Neue Issues direkt in Ihr Postfach

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