python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.42k stars 2.82k forks source link

Value of type <nothing> is not indexable #8829

Open rggjan opened 4 years ago

rggjan commented 4 years ago

See the following example:

from typing import Any, Optional, TypeVar

T = TypeVar("T")

def assert_not_none(value: Optional[T]) -> T:
    assert value is not None
    return value

def foo1(a: Optional[Any]) -> int:
    return assert_not_none(a)[3]

def foo2(a: Optional[Any]) -> int:
    assert a is not None
    return a[3]

I would expect that foo1 and foo2 are equivalent. However, running mypy on this file, I get:

test.py:12: error: Value of type <nothing> is not indexable

For some reason, assert_not_none doesn't map Optional[Any] to Any, as it is supposed to (and which would accept the indexing), but instead maps it to <nothing> which throws an error. The second version with asserting that it is not None seems to work fine, though.

msullivan commented 4 years ago

Definitely a bug and a somewhat surprising one too. Probably an issue in constraints.py?