如何为Python类方法的装饰器添加正确的类型注解?
问题:为类方法编写可访问self的装饰器的类型注解
我有一个包含多个相似方法的类:
class Actions: def action1(self, parameter1: int) -> None: ... def action2(self, parameter2: int) -> None: ...
我想要为这些方法创建一个可访问self的装饰器,基本结构如下:
def action(method: Callable[???]) -> Callable[???]: def wrapper(self, *args, **kwargs) -> None: method(self, *args, **kwargs) ... return wrapper
请问该装饰器的类型注解应该如何编写?
我目前尝试了如下写法(其中Actions是仅包含必要属性的协议类):
from typing_extensions import Concatenate, ParamSpec from typing import Callable P = ParamSpec("P") def action( method: Callable[Concatenate[Actions, P], None] ) -> Callable[Concatenate[Actions, P], None]: def wrapper(self: Actions, *_args: P.args, **kwargs: P.kwargs) -> None: method(self, *args, **kwargs) ...
这段代码在Mypy中可以正常识别,但PyCharm会对类似actions.action1(parameter1=0)的调用报错:Expected type 'Actions', got 'int' instead。
内容的提问来源于stack exchange,提问作者Данила Мамутов
相关产品推荐
相关产品推荐

