Document how to declare dependant types in method signatures
I have several TypedDict:
TerminateHandlerContextType = TypedDict( "TerminateHandlerContextType",{...},)
CrashHandlerContextType = TypedDict( "CrashHandlerContextType", {... },)
QuitHandlerContextType = TypedDict("QuitHandlerContextType", {...})
And then related Callable:
TerminateHandlerType = Callable[[TerminateHandlerContextType], None]
QuitHandlerType = Callable[[QuitHandlerContextType], None]
CrashHandlerType = Callable[[CrashHandlerContextType], None]
If I then declare a method that depends of both:
def _call_handler(
self,
handler: Union[
TerminateHandlerType, QuitHandlerType, CrashHandlerType
],
context: Union[
TerminateHandlerContextType, QuitHandlerContextType, CrashHandlerContextType,
],
):
...
return handler(context) # <---- MYPY COMPLAINS HERE
Then mypy complains, because, while I always ensure logically that the proper handler is called with the proper context, it can't see that.
I couldn't find in the documentation a way to tell it that the context type depends on the handler type. I assume it's either a Generic, or a TypeVar, but didn't find the solution.
mypy 0.770 python 3.6
Yes a TypeVar is right. I'd do something like this:
HandlerT = TypeVar("HandlerT", TerminateHandlerContextType, CrashHandlerContextType, QuitHandlerContextType)
def _call_handler(self, handler: HandlerT, context: Callable[[HandlerT], None]):
return handler(context)
Thanks. The documentation show many examples with containers, and TypeVar to link the params to the output type. It makes sense you can also use it for Callable, and to link parameters together, but I must say it didn't occur to me.
The documentation has seen some lengthy improvements since this issue was opened. I see that the current documentation includes examples of using Callable with type variables. Is anything else required for this issue?