Closed
Description
🐛 Bug Report
- Create a file
tmp.py
with this code:
from typing import TypeVar, Union
TDefault = TypeVar('TDefault')
def f(flag: int, default: TDefault = None) -> Union[int, TDefault]:
if flag == 0:
return default
return flag
- Run mypy on the file.
Expected Behavior
No type errors.
Actual Behavior
tmp.py:6: error: Incompatible return value type (got "Optional[TDefault]", expected "Union[int, TDefault]")
Found 1 error in 1 file (checked 1 source file)
To be more specific, mypy fails to realize that the none-returning-path is just a different default-returning-path (where TDefault happens to correspond to NoneType), rather than a mistake.
To avoid the error I have to specify the type information in each case manually using overloads:
from typing import TypeVar, Union, overload
TDefault = TypeVar('TDefault')
@overload
def f(flag: int) -> Union[int, None]:
pass
def f(flag: int, default: TDefault) -> Union[int, TDefault]:
pass
def f(flag, default = None):
if flag == 0:
return default
return flag
Your Environment
- Mypy version used: 0.782
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini
(and other config files): None - Python version used: 3.8.5
- Operating system and version: gLinux