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.
See the following example:
I would expect that
foo1
andfoo2
are equivalent. However, runningmypy
on this file, I get:test.py:12: error: Value of type <nothing> is not indexable
For some reason,
assert_not_none
doesn't mapOptional[Any]
toAny
, 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.