-
-
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
Typing of method decorators not working properly [question] #10805
Comments
I think mypy is doing the right thing by emitting an error here. Pyright also emits an error in the same place. You are replacing the method In short, you're confounding the type analyzer by indicating that the decorated type is a class instance when it's really a method. The annotated types are not consistent with your implementation. A consistent implement would look like the following. This does generate a runtime exception in the way that mypy indicates it will. class CountedFunction(Generic[T]):
def __init__(self, func: T):
self.count = 0
self.func = func
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
def counter(func):
return CountedFunction(func)
...
print(greet("John")) # OK
...
print(a.greet("John")) # TypeError: A.greet() missing 1 required positional argument: 'name' I don't see a good way to properly annotate the implemented code. Perhaps someone else has some ideas. |
Anyone has an idea to annotate the |
Hi. It seems that the typing of decorators is problematic with functions inside classes.
Suppose we want to see how many times a function has been called, we can write a simple decorator:
and use it like:
To type this
counter
decorator, we can:This is fine with functions outside classes. However, it is not with a
class functionmethod:We get static errors from mypy, although the code can be run without any runtime errors:
Full code (click to expand)
The text was updated successfully, but these errors were encountered: