How can we annotate a decorator that works with functions and methods? #1357
NeilGirdhar
started this conversation in
General
Replies: 1 comment 4 replies
-
Isn't the problem with decorators for methods more that the type checker doesn't know it is supposed to bind the self argument? If you have a decorator like this: def decorator(f: Callable[P, R]) -> Callable[P, R]:
f.my_attribute = 4 # type error
return f
class C:
@decorator
def m(self, x: int) -> int:
return 2 * x
c = C()
reveal_type(C.m)
reveal_type(c.m)
print(c.m(4))
print(c.m.my_attribute) # type error then type checkers can infer the signature of It seems to me what's needed is a way to define subclasses of functions, so that they still get bound as methods but can have additional attributes. |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
It appears to be impossible to perfectly annotate a decorator that works on both functions or methods. In particular, it's practically impossible to implement the
__get__
method.It is also currently impossible to natively (without plugins) annotate
functools.partial
. Even a MyPy plugin has proved to be very difficult.I propose adding
typing.PartialApplication
to:__get__
,functools.partial
.Consider trying to create a decorator
jit
that works with both bare functions and methods. The problem is that in the method case, it has to respond to__get__
and strip off the first argument. It seems that we can only do this withConcatenate
:We can't seem to deal with the method case alongside the function case. Here's the proposed solution:
The idea is that
PartialApplication
takes aParamSpec
argument and returns it less thatParamSpec
's first positional parameter. It verifies that this removed parameter matches its second argument.This could be generalized to
ParamSpec.args
as its second argument), orTypedDict
orParamSpec.kwargs
as its third argument).Idealized example with
partial
(might need some tweaks)Beta Was this translation helpful? Give feedback.
All reactions