mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Type is lost after merge with `Union[Any, None]`

Open cdce8p opened this issue 3 years ago • 0 comments

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

cdce8p avatar Sep 17 '22 13:09 cdce8p