Automatically use `Self` type even if it doesn't appear in method annotation
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- Ø Merge
- 1 T. 18 Std.
- Gemergte PRs (30 T.)
- 54
Beschreibung
This is a follow up for https://github.com/python/mypy/pull/14041
This example gives an error:
from typing import Self
class C:
x: Self
def meth(self) -> None:
self.x = self # E: Incompatible types in assignment (expression has type "C", variable has type "Self")
Although it is unfortunate, technically this is required by PEP 484, that says that if no annotation is given, self has a type of current class (note also we can't bind self type for self.x expression giving it type C, as this will open another unsafety). This can be avoided by using e.g. self: Self (or generally Self type anywhere in the signature).
It looks like there can be only two solutions:
- Always infer
Selftype forself. This will cause a big performance penalty and may be surprising for users who are not familiar withSelf(if they usereveal_type(self)). - Use some heuristic and only infer
Selfwhere otherwise we will have this problem. For example, inferSelfif an attribute with type containingSelfis used anywhere in a method.
I am leaning towards the latter, but didn't want to do this until we get some more experience.
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 ergänzenden Kontext in PR #14041 zu lesen und das Beispiel mit Self und self.x = self zu reproduzieren. Überprüfe das relevante Verhalten von PEP 484 und vergleiche die beiden vorgeschlagenen Ansätze zur Inferenz. Als erledigt gilt die Aufgabe, wenn ein Ansatz feststeht und das Beispiel typgeprüft wird, ohne die genannte Unsicherheit oder unbeabsichtigtes breit gefasstes Verhalten einzuführen.
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
- Muss geklärt werden
- Anfängerfreundlichkeit
- 25/100