mypy is not evaluating Union[X, Y] from Type[Union[X, Y]] over (cl: Type[T]) -> T function

Viewed 32

This code:

def structure(obj: Any, cl: type[str]) -> str:
    reveal_type(cl)
    reveal_type(converter.structure)
    data = converter.structure(obj, cl)
    reveal_type(data)
    return data

is evaluated without errors by mypy:

note: Revealed type is "Type[builtins.str]"
note: Revealed type is "def [T] (obj: Any, cl: Type[T`2]) -> T`2"
note: Revealed type is "builtins.str"

But this code, where I just changed str to Union[int, str]:

def structure(obj: Any, cl: type[Union[int, str]]) -> Union[int, str]:
    reveal_type(cl)
    reveal_type(converter.structure)
    data = converter.structure(obj, cl)
    reveal_type(data)
    return data

fails with the following error when evaluated by mypy:

note: Revealed type is "Union[Type[builtins.int], Type[builtins.str]]"
note: Revealed type is "def [T] (obj: Any, cl: Type[T`2]) -> T`2"
note: Revealed type is "builtins.object"
error: Incompatible return value type (got "object", expected "Union[int, str]")

Shouldn't it say:

note: Revealed type is "Union[builtins.int, builtins.str]"

instead of

note: Revealed type is "builtins.object"

on the third note?

The converter is a cattrs converter. I'm using mypy 0.971 with Python 3.9.13.

0 Answers
Related