Using type Self allows to violate Liskov Substitution Principle
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
By using Self in the type of a method's argument it's possible to violate the Liskov Substitution Principle without any warning.
(A clear and concise description of what the bug is.)
To Reproduce
Mypy raises no issue on this code although SubClass.update is clearly violating LSP.
from typing_extensions import Self
class BaseClass:
foo: int
def update(self, other: Self) -> None:
self.foo = other.foo
class SubClass(BaseClass):
bar: int
def update(self, other: Self) -> None: # problem here
super().update(other)
self.bar = other.bar
Expected Behavior
I'd expect that using Self would raise the warning similarly to specifying the class. Mypy raises the issue on the below.
from typing_extensions import Self
class BaseClass:
foo: int
def update(self, other: BaseClass) -> None:
self.foo = other.foo
class SubClass(BaseClass):
bar: int
def update(self, other: SubClass) -> None: # problem here
super().update(other)
self.bar = other.bar
Your Environment
- Mypy version used: 1.4.1
- Python version used: 3.10.8
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, den Python-Reproducer im Issue auszuführen, und vergleiche das auf Self basierende Override mit den expliziten Annotationen von BaseClass und SubClass. Verfolge mypys Override-Prüfung für Methodenparameter, die Self verwenden, und füge dann Regressionstests für den gemeldeten Fall hinzu. Fertig ist es, wenn mypy das ungültige Override meldet und gleichzeitig die gültige Verwendung von Self beibehält.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers, devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 42/100