python / python/mypy

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

Aperta
#14,075 3 commenti 5 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature topic-self-types
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia leggendo il contesto di follow-up in PR #14041 e riproducendo l’esempio con Self e self.x = self. Esamina il comportamento rilevante di PEP 484 e confronta i due approcci di inferenza proposti. Il lavoro è completato quando si concorda un approccio e l’esempio supera il controllo dei tipi senza introdurre l’insicurezza indicata o un comportamento involontariamente troppo ampio.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.