Skip to content

while x is not None not recognised by Optional type #10637

Closed
@dlehmenk

Description

@dlehmenk

Bug Report

I have a list with type List[Optional[X]] and a loop over it:

from typing import List, Optional

a: List[Optional[str]] = [None, None, None]

for node in ['a','b','c']:
     o = len(node)

     while a[o] is not None:
         somestr: str = a[o]

(yes, this does absolutely nothing, for a more complete example see mypy_bug.py.txt. But the bug is the same.)

Mypy shows the following error: tmp.py:9: error: Incompatible types in assignment (expression has type "Optional[str]", variable has type "str"). But a[o] can never be None, because of the loop, and thus has to be str, if this code is executed.

To Reproduce

Check the code posted above with mypy.

Expected Behavior

No error should be shown, since the types are correct (IMHO)

Your Environment

  • Mypy version used: 0.761
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: Python 3.8.5
  • Operating system and version: Ubuntu 20.04.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions