I have the following python code:
from typing import TypeVar, Callable, Optional
import os
T = TypeVar("T")
def config(key: str, default: Optional[T] = None, cast: Callable[[str], T] = lambda x: x) -> T:
value = os.environ.get(key)
if value is None:
if default is None:
raise KeyError()
return default
return cast(value)
When I run it through pyright it doesn’t give me any errors. But mypy give me two errors:
error: Incompatible default for argument "cast" (default has type "Callable[[str], str]", argument has type "Callable[[str], T]") [assignment]
error: Incompatible return value type (got "str", expected "T") [return-value]
I also tried making cast optional with a default value of None then in the function body I check if cast is None, I return value as is otherwise I run it through cast. This resolves the first error but the second error persists.
Is there a way to correctly type this function in mypy without loosening the types with something like Any
or returning T | str
?