TypeVar bound doesn't understand CRTP
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
Ideally, this snippet would work. It enables making multiple types that share the same implementation but don't subclass each other (like newtype in other languages). If you comment out the other.quack() call and the bound="Foo[DerivedT]") then it will typecheck -- the issue is specifically with being able to express a typevar bound indicating the typevar has a base class that uses that typevar as a generic parameter.
#!/usr/bin/env python
from __future__ import annotations
from typing import Generic, TypeVar
DerivedT = TypeVar("DerivedT", bound="Foo[DerivedT]")
class Foo(Generic[DerivedT]):
def quack(self) -> None:
print("quack!")
def quack_together(self, other: DerivedT) -> None:
self.quack()
other.quack()
class Bar(Foo[Bar]): pass
x = Bar()
y = Bar()
x.quack_together(y)
$ python -m mypy --strict /tmp/self_test.py
self_test.py:6: error: Type variable "self_test.DerivedT" is unbound [valid-type]
self_test.py:6: note: (Hint: Use "Generic[DerivedT]" or "Protocol[DerivedT]" base class to bind "DerivedT" inside a class)
self_test.py:6: note: (Hint: Use "DerivedT" in function signature to bind "DerivedT" inside a function)
Found 1 error in 1 file (checked 1 source file)
- Mypy version used: mypy 1.10.0 (compiled: yes)
- Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: 3.12
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
Der Reproducer befindet sich in /tmp/self_test.py; beginne damit, python -m mypy --strict /tmp/self_test.py mit der gezeigten CRTP-Beschränkung auszuführen. Untersuche, wie mypy die ungebundene TypeVar meldet, und betrachte die Arbeit als abgeschlossen, wenn das Beispiel ohne diesen Fehler eine Typprüfung besteht und dabei die beschriebene Typbeziehung erhalten bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100