python / python/mypy

Cannot determine type of attribute due to circular reference:

Aperta
#10,749 0 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Is this a bug?

The following code (playground link)...

class X:
    def __init__(self, value: str | None = None, parent: X | None = None) -> None:
        if value is None:
            if parent is not None and parent.value is not None:
                value = "something"
            else:
                value = "something_else"
        reveal_type(value)
        self.value = value

Produces this output...

main.py:4: error: Cannot determine type of "value"
main.py:8: note: Revealed type is "builtins.str"

Here, it's clear that the type of X.value is a string, as indicated by reveal_type, but MyPy is unable to realize this by the time we reach parent.value.

The solution is to forward declare the type of X.value:

class X:
    def __init__(self, value: str | None = None, parent: X | None = None) -> None:
        self.value: str
        if value is None:
            if parent is not None and parent.value is not None:
                value = "something"
            else:
                value = "something_else"
        self.value = value

But that doesn't seem necessary given that resolving the circular reference is not strictly required to figure out what the type of X.value is.

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 dal mypy playground collegato e riproduci l’esempio con mypy 0.910, Python 3.10 e strict mode. Traccia l’inferenza attorno a parent.value e self.value nel percorso pertinente del controllo dei tipi. Il lavoro è concluso quando l’esempio non segnala più che il tipo di value non può essere determinato, mantenendo il tipo str rivelato.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.