super() is analyzed differently from super(C, self) in generic subclass context
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
Consider a minimal reproducing example, based on one from #7362
from typing import TypeVar
T = TypeVar('T', str, int)
class C(list[T]):
def pop_item(self, key: int) -> T:
reveal_type(super().pop(key))
return super().pop(key)
(https://mypy-play.net/?mypy=0.961&python=3.10&gist=ab00ab8ee474443b979cb00ea4284946)
main.py:7: note: Revealed type is "T`1"
main.py:8: error: Incompatible return value type (got "T", expected "str")
main.py:8: error: Incompatible return value type (got "T", expected "int")
This is clearly unexpected, as this should work normally. However, if instead of writing super(), we write super(C, self), which is exactly equivalent syntactically in Python 3, we get
from typing import TypeVar
T = TypeVar('T', str, int)
class C(list[T]):
def pop_item(self, key: int) -> T:
reveal_type(super(C, self).pop(key))
return super(C, self).pop(key)
(https://mypy-play.net/?mypy=0.961&python=3.10&gist=44206838005bf4acfa264a42eecb0eb5)
main.py:7: note: Revealed type is "builtins.str"
main.py:7: note: Revealed type is "builtins.int"
As expected.
Possible fix
Here, Mypy is analyzing super(), differently from super(C, self), which is syntactically incorrect. If super() would instead be (correctly) parsed as super(C, self) in this case, the problem disappears. Note that this also fixes #7362 and #10130.
I don't know enough about Mypy internals to understand why Mypy does not take super() to be equal to super(C, self) here, but perhaps this could be an easy fix?
2024 edit
This reproduces on 1.8.0 as well.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, das minimale reproduzierbare Beispiel aus dem Issue in mypy oder den verlinkten mypy-play-Fällen auszuführen, und vergleiche bare super() mit super(C, self). Verfolge, wie jede Form im Kontext einer generischen Subklasse analysiert wird. Als abgeschlossen gilt die Untersuchung, wenn beide Formen denselben konkreten Typ anzeigen und die return-Anweisung ohne Fehler aufgrund inkompatibler Typen akzeptiert wird.
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
- Klar beschrieben
- Anfängerfreundlichkeit
- 35/100