Closed
Description
Mypy doesn't support a function that tries to return a generic callable. I wonder if mypy could make this code work properly:
from typing import TypeVar, Callable, Any
T = TypeVar('T', bound=Callable[..., Any])
def deco() -> Callable[[T], T]:
def inner(x):
return x
return inner
@deco()
def g(x: str) -> int: ...
g('') # should be fine? currently "Argument 1 to "g" has incompatible type "str"; expected None"
g(1) # should be an error
Metadata
Metadata
Assignees
Labels
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
rwbarton commentedon May 18, 2016
This is related to my comments at #1317, but maybe worth keeping open as a separate issue.
rwbarton commentedon Jun 13, 2016
As Jukka and I discussed at PyCon, this situation where a type variable appears only in the result type of a generic callable could be handled by "floating in" the type variable to the result type: instead of
give
deco
the typeI wonder how often this arises in practice?
JukkaL commentedon Jun 13, 2016
The only case where I remember having seen this is in a decorator that is used like this:
The decorator, when called, returns a generic function
T
->T
that preserves the signature of the decorated function.sharmaeklavya2 commentedon Jul 22, 2016
At Zulip, we're using such decorator-returning functions a lot. One of these decorator-returning functions, named
cache_with_keys
, is applied to dozens of functions, many of which are called hundreds of times (see zulip/zulip#1348). It'll be great to see this issue fixed since a lot of our code is not properly type checked because of this.jstasiak commentedon Aug 10, 2016
I have another example from our codebase:
Both of the decorators returned by
app.route()
andrate_limit()
at lest formally preserve the signature of the callable being decorated.Sadly I don't have enough knowledge to help with this myself.
gnprice commentedon Aug 11, 2016
This seems like something we'll really want to fix, but it's not immediately clear yet what the fix looks like.
roganov commentedon Oct 15, 2016
As a workaround, rewriting nested functions to a class seem to work:
gvanrossum commentedon Oct 15, 2016
Oooh, very clever! I can't say I personally understand how it works, and we
should still fix the original error, but this looks like a useful
workaround. Thanks!
On Sat, Oct 15, 2016 at 4:28 AM, Yegor Roganov notifications@github.com
wrote:
--Guido van Rossum (python.org/~guido)
32 remaining items