Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document how to declare dependant types in method signatures #8662

Open
ksamuel opened this issue Apr 12, 2020 · 2 comments
Open

Document how to declare dependant types in method signatures #8662

ksamuel opened this issue Apr 12, 2020 · 2 comments

Comments

@ksamuel
Copy link

ksamuel commented Apr 12, 2020

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

@JelleZijlstra
Copy link
Member

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)

@ksamuel
Copy link
Author

ksamuel commented Apr 19, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants