Invalid type inferred for attribute initialized to `None` in class body

Aperta
#4,416 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

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

Direzione di ricerca

Start with the reproducer in the issue and compare inference for class attributes with the shown global-variable case, including strict and non-strict optional checking. Trace the type-inference entry point that handles assignments in class bodies; done means the chosen behavior is implemented and regression coverage verifies the resulting revealed types.

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

Descrizione

bug priority-1-normal

The type inferred for attribute x in the fragment below is unexpected (I was using --strict-optional):

class A:
    x = None
    y = None

    def __init__(self):  # Note: no annotation
        self.x = 1

    def g(self) -> None:
        self.y = 1

a = A()
reveal_type(a.x)  # None  <---- unexpected
reveal_type(a.y)  # Union[int, None]

if a.x is not None:
    1 + ''  # No error, because mypy considers this unreachable

Union[None, Any] would be a better inferred type for A.x. It would work around the false negative. This would be consistent with how global variables work:

x = None

def f():
    global x
    x = 1

reveal_type(x)  # Union[Any, None]

When not using strict optional checking, the type of A.x is currently also None. Any would be a better inferred type in that case.

Another alternative would be to require annotations for both x and y, since inferring a useful (non-None) type requires non-local context. This would be my preference if we didn't have existing code to worry about -- this could require a large number of additional annotations for code that currently type checks cleanly. A final option would be to only require an annotation for y and infer Union[None, Any] for x, since x is initialized in an unannotated method.

[Note that use of non-local context (outside current scope) can make fine-grained incremental checking harder to implement.]

Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Merge medio
1g 18h
PR unite (30g)
54

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.

Altre issue di python/mypy

Tutte le issue di python/mypy

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.