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

Ouverte
#4,416 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
38/100
Type d'issue
Bug
Clarté
Plutôt claire
Activité
À l'abandon
Stack technique
python
Domaine
compilers, devtools

Piste de recherche

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.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

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.]

Langage dominant
Python
Étoiles
20.6k
Forks
3.3k
Merge moyen
1 j 18 h
PR mergées (30 j)
54

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de python/mypy

Toutes les issues de python/mypy

Issues similaires

Plus d'issues Python

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.