I have a Python function with an input parameter, the value of which controls the type of the return value. The parameter may be omitted (default value None), in which case a module level variable is used. This way, the default behavior can be changed by changing the module level variable.
A minimal example:
from typing import overload, Union, Literal, Optional
option_default: Literal["str", "int"] = "int"
@overload
def test(option: Literal["str"]) -> str:
...
@overload
def test(option: Literal["int"]) -> int:
...
@overload
def test(option: Literal[None] = None) -> Union[str, int]:
...
def test(option: Optional[Literal["str", "int"]] = None) -> Union[str, int]:
if option is None:
option = option_default
if option == "str":
return "foo"
else:
return 1
foo: int = test() # Incompatible types in assignment (expression has type "Union[str, int]", variable has type "int")
option_default = "str"
baz: str = test() # Incompatible types in assignment (expression has type "Union[str, int]", variable has type "str")
Normally one would use typing.overload to deal with this sort of situation. However, for test() without arguments that doesn't work--hence the mypy errors. Is there a better way to provide type info here?