Skip to content

False negative involving null checks on optional types #5423

Closed
@person594

Description

@person594

Here is a minimal program demonstrating the problem:

foo = None
for _ in range(2):
  if foo is not None:
    print(1[2])
  foo = 1

Expected behavior:
error: Value of type "int" is not indexable

Actual behavior:
mypy accepts the program as valid, when run with the --strict flag

This issue seems to be a problem with how mypy handles reassignment to None type variables, and static evaluation of conditionals. After line 1, foo has the type None according to mypy. Thus, mypy determines that the condition on line 3 will never hold, and thus doesn't do type checking for the body of the if statement. On line 5, foo's type changes to Optional[int]. This, however, will only be reflected in code that follows line 5.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions