-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Decorated function leaks type variables #11816
Comments
The I think what you want is this: C = TypeVar("C", bound=Callable[..., Any])
def api_boundary(f: C) -> C:
return f |
@erictraut Okay, thanks! Out of curiosity, would I have been able to do it my way after PEP 612 is completely implemented? |
Yes, you could have used a P = ParamSpec("P")
def api_boundary(f: Callable[P, R]) -> Callable[P, R]:
return f This works today in pyright. I think I read that the next release of mypy will contain support for this case. |
I'm going to reopen this until mypy supports it. Here's another example: from functools import partial
from typing import Callable, Generic, TypeVar
from typing_extensions import ParamSpec
R = TypeVar('R')
X = TypeVar('X')
P = ParamSpec('P')
class custom_vjp(Generic[P, R]):
def __init__(self, fun: Callable[P, R], x: int = 0):
self.fun = fun
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
return self.fun(*args, **kwargs)
@custom_vjp
def replace_cotangent(x: X, new_cotangent: X) -> X:
return x
reveal_type(replace_cotangent(1, 2))
|
More examples discovered today from my use of custom context manager decorators: https://mypy-play.net/?mypy=0.930&python=3.10&gist=06b8b06ca6bf78674c19c123b98c47ce Interestingly, importing the The issue seems to be that using ParamSpec with generic decorators/callables seem to lose the ability to determine generic types through calls to the decorated function. I debated making this example a separate |
My example above started working on mypy 0.920 with initial support for ParamSpec and broke in 0.930, and is still broken on master, if that helps narrow down a diff. |
I believe this is now fixed with the last ParamSpec PR. |
Yes, I can't immediately reproduce any of the |
Hey Alex, how did you test using the master branch? mypy-play.net still produces the errors in this thread with the master branch option but I don't know if it's using the most up-to-date "master branch." Do you build mypy locally and test with that copy? |
Yeah, the "mypy master" option on mypy playground isn't a reliable tool really — it often isn't quite up to date 😕 There's setup instructions here for how to get mypy running locally: https://github.com/python/mypy/blob/master/CONTRIBUTING.md. Feel free to ping me if you run into any difficulties! After following those instructions, just run |
This is on Mypy 0.921.
Or maybe I've misunderstood type inference, and just have to wait for PEP 612 to finish being implemented?
The text was updated successfully, but these errors were encountered: