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

Open
#4,416 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
38/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python

Research direction

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.

Written by the indexing model from the issue text.

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

Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.