mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Document how to declare dependant types in method signatures

Open ksamuel opened this issue 5 years ago • 3 comments

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

ksamuel avatar Apr 12 '20 07:04 ksamuel

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)

JelleZijlstra avatar Apr 12 '20 16:04 JelleZijlstra

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.

ksamuel avatar Apr 19 '20 10:04 ksamuel

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?

brianschubert avatar Oct 07 '24 13:10 brianschubert