Closed as not planned
Closed as not planned
Description
Bug Report
A TypeVar bound to Union[x, y]
will resolve to x
after an if isinstance(..., x)
is used which is incompatible with the return type.
I'm not sure on how to describe exactly what is going on, better check the Example.
Also mypy experts, please forgive me if that is intended behavior and not a bug (I would appreciate a working solution in this case :)
To Reproduce
Example:
from typing import TypeVar, Union
T = TypeVar("T", bound=Union[str, int])
def a(x: T) -> T:
if isinstance(x, str):
return x
return x
Expected Behavior
I expect that this definition is correct, since whatever input is given, the output is the same.
Actual Behavior
mypy raises error: Incompatible return value type (got "str", expected "T")
.
Further Info
- I want to have the
str -> str
,int -> int
mapping, so simply usingUnion[str, int]
won't work. - This function is called sometimes with variables of type
Union[str, int]
, so usingTypeVar("T", str, int)
won't work either.
Your Environment
- Mypy version used: 0.950
- Mypy command-line flags: --strict
- Mypy configuration options from
mypy.ini
(and other config files): - Python version used: 3.9
- Operating system and version: win10