Allow a base class to restrict the type of subclass's inner class
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Feature
For regular classvars, attributes and methods, mypy already checks that the types in a subclass match those declared in the superclass. However, this checking does not extend to inner classes in the subclass. It seems inner classes are ignored by mypy entirely.
For example, a framework could define an abstract class Model whose inner class Meta must implement a certain protocol:
# Defined in the framework
class InnerMetaProtocol(Protocol):
example_attr: str
class Model:
Meta: type[InnerMetaProtocol]
# An application developer using framework
class Widget(Model):
class Meta:
example_attr = 123 # This should be an error: int is not str
Class Widget implements Model, whose attribute Meta should conform to type[InnerMetaProtocol], meaning it requires attribute example_attr: str. But currently mypy ignores this constraint: Playground.
It's probably useful to support this with not just protocols, but also concrete classes (e.g. Meta: type[ConcreteClass]).
Pitch
This pattern of inner Meta classes is used quite extensively in the Django ecosystem, including for Django models, forms, Django REST Framework serializers, djangorestframework-dataclasses, etc. I'm sure there are other use cases as well, but I don't know off the top of my head.
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 mit dem Playground-Beispiel des Issues und vergleiche den deklarierten Typ von Model.Meta mit der inneren Meta-Klasse der Unterklasse. Die Arbeit ist abgeschlossen, wenn mypy das inkompatible int-Beispiel meldet und die angegebenen Fälle für Protokoll und konkrete Klasse unterstützt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100