How to type the self
argument in a Protocol
for a decorator?
#9402
-
Originally asked this on Discord, but nobody was able to help there. How should I type the following: import functools
from typing import Protocol
class Method[S: SomeClass, R, **P](Protocol):
def __call__(_, self: S, *args: P.args, **kwargs: P.kwargs) -> R: ...
def decorator[S: SomeClass, R, **P](f: Method[S, R, P]) -> Method[S, R, P]:
@functools.wraps(f)
def wrapper(self: S, *args: P.args, **kwargs: P.kwargs) -> R:
return f(self, *args, **kwargs)
return wrapper
class SomeClass:
@decorator
def a_method(self) -> int: ...
instance = SomeClass()
instance.a_method() I want to indicate that the decorator only works on methods of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
This is a known limitation of Pyright will retain this internal information when using a def decorator[S: SomeClass, R, **P](f: Callable[Concatenate[S, P], R]) -> Callable[Concatenate[S, P], R]: ... This retains the information that the decorated method is an instance method and should be bound when accessed through an instance of |
Beta Was this translation helpful? Give feedback.
Pyright treats
self
andcls
as positional-only in this case. This hasn't yet been clarified in the typing spec, but there seems to be general consensus that it should be. See here.