In Python, I have the following function:
T = TypeVar("T")
def handle_func(x: int, func: Callable[[int], T]) -> T:
return func(x)
And I can use it so:
handle_func(1, lambda x: x + 1)
handle_func(1, lambda x: x == 1)
When I run MyPy, all is good.
But… How can I add a default value to func
?
When I do this:
def handle_func(x: int, func: Callable[[int], T] = lambda x: x + 1) -> T:
return func(x)
and run MyPy I get:
error: Incompatible default for argument "func" (default has type "Callable[[int], int]", argument has type "Callable[[int], T]") [assignment]
error: Incompatible return value type (got "int", expected "T") [return-value]
But it works when the default is not there… How can I type this? What am I understanding incorrectly?