Skip to content

Assert not None not correctly identified for Optional #5528

@hros

Description

@hros

According to previous topics mypy should recognize that and Optional is not None following an assertion.
This does not work properly for containers of Optional, as demonstrated by the following code:

from typing import Optional, List

def f1(a: Optional[int], b: int)->int:
    assert a is not None
    b = a
    return b

def f2(a: List[Optional[int]], i: int, b: int)->int:
    assert a[i] is not None
    b = a[i]
    return b

def f3(a: List[Optional[int]], i: int, b: int)->int:
    ai = a[i]
    assert ai is not None
    b = ai
    return b

in f2 mypy gives an error about incompatibility of Optional[int] and int, whereas in f1 it correctly infers that the Optional is not None.
adding an assignment ai=a[i] in function f3 "solves" the problem.
can't mypy infer that the index i is not being modified and understand the assert a[i] is not None?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions