Taking the example from the json module docs:
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
What would be the proper way to add type hints here? My naive approach with using a TypedDict and overloads fails:
from typing import Any, Dict, TypedDict, TypeVar, Union, overload
_T = TypeVar('_T', bound=Dict[str, Any])
class JSONDict(TypedDict):
__complex__: Any
real: float
imag: float
@overload
def as_complex(dct: JSONDict) -> complex: ...
@overload
def as_complex(dct: _T) -> _T: ...
def as_complex(dct: _T) -> Union[complex, _T]:
if '__complex__' in dct:
return complex(dct['real'], dct['imag'])
return dct
as mypy objects with:
main.py:14: error: Overloaded function signatures 1 and 2 overlap with incompatible return types
main.py:19: error: Overloaded function implementation cannot satisfy signature 1 due to inconsistencies in how they use type variables
Playground gist, should you want to try the sample out in the browser.