python / python/mypy

Automatically use `Self` type even if it doesn't appear in method annotation

Offen
#14,075 3 Kommentare 5 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

feature topic-self-types
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 Self type for self. This will cause a big performance penalty and may be surprising for users who are not familiar with Self (if they use reveal_type(self)).
  • Use some heuristic and only infer Self where otherwise we will have this problem. For example, infer Self if an attribute with type containing Self is 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

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Ö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

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.