mypy
mypy copied to clipboard
Type is lost after merge with `Union[Any, None]`
Bug Report
from typing import Any
def func(d: dict[int, Any]) -> None:
x: int | None
x = d.get(1)
reveal_type(x) # typing is lost -> Union[Any, None]
d.get get's correctly inferred as Any | None. However, merging the existing type int | None with Any | None results in Any | None. I.e. mypy looses the original type information. That is unexpected.
Comparing it to a type merge with just Any:
def f(a: Any) -> None:
x: int | None
x = a
reveal_type(x) # int | None
In this case x retains the type information, as expected.
--
Another example which doesn't rely on dict.get
def g(a: Any | None) -> None:
x: int | None
x = a
reveal_type(x) # typing is lost -> Union[Any, None]
Expected Behavior
Mypy should retain the original type information even after merging it with Any | None.
Your Environment
- Mypy version used: 0.971