Covariant type variables should be allowed in class method
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Currently, covariant type variables are allowed in __init__ so that you can put create an immutable containers with something inside of it. See https://github.com/python/mypy/issues/2850.
It would be useful if covariant types are also allowed in class method that serve as alternative constructors. Currently mypy errors on this example, which is an extension of the other issues example:
from typing import Generic, TypeVar
T_co = TypeVar("T_co", covariant=True)
class C(Generic[T_co]):
def __init__(self, x: T_co) -> None:
...
@classmethod
def custom_init(cls, x: T_co) -> "C[T_co]":
# error: Cannot use a covariant type variable as a parameter
return cls(x)
My use case is trying to define an immutable container protocol that has a create class method, which will initialize the container with some contents, like this:
T_cov = typing.TypeVar("T_cov", covariant=True)
class ListProtocol(typing_extensions.Protocol[T_cov]):
@classmethod
def create(cls, *items: T_cov) -> "ListProtocol[T_cov]":
...
def getitem(self) -> T_cov:
...
...
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 Problem anhand der classmethod-Beispiele im Bericht zu reproduzieren, und untersuche, wie mypy kovariante Typvariablen in Methodenparametern validiert. Definiere das beabsichtigte Verhalten für alternative Konstruktoren, füge dann Regressionstests hinzu, die die akzeptierten Fälle zeigen, und führe die relevanten Type-Checker-Tests aus.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- tooling
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100