python / python/mypy

"Cannot determine type" if first assignment to attribute is unreachable

Aperta
#9,709 0 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-inference topic-reachability
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

To Reproduce

Run mypy on the following code:

class C:
    def __init__(self, a: str) -> None:
        if a is None:
            self.x = 123
        else:
            self.x = 456

It will output:

testcase.py:6: error: Cannot determine type of 'x'

Line 6 contains the second assignment to self.x.

Expected Behavior

mypy should be able to determine that the type of C.x is int.

Actual Behavior

The fact that a is annotated as str means that mypy determines that a is None is never true and therefore the first assignment to self.x is unreachable. The problem disappears if a is annotated as Optional[str].

So it looks like mypy half-ignores the first assignment to self.x: it doesn't use the type information available there since the code is unreachable, but it still considers it the assignment that determines the type of self.x.

Your Environment

mypy 0.790 with default configuration, running on Python 3.8.5 on openSUSE Linux.

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 con il riproduttore Python fornito e segui l’inferenza dei tipi di mypy per la prima assegnazione di attributo quando il flusso di controllo contrassegna quel ramo come irraggiungibile. Conferma la correzione eseguendo nuovamente mypy sull’esempio: C.x dovrebbe essere inferito come int senza errori, mentre il caso Optional[str] dovrebbe continuare a funzionare.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.