我有一个装饰器,它接受一个函数并返回具有一些附加属性的相同函数:
import functools
from typing import *
def decorator(func: Callable) -> Callable:
func.attr1 = "spam"
func.attr2 = "eggs"
return func
Run Code Online (Sandbox Code Playgroud)
如何键入提示的返回值decorator?我希望类型提示传达两条信息:
Callableattr1和attr2如果我写一个协议,
class CallableWithAttrs(Protocol):
attr1: str
attr2: str
Run Code Online (Sandbox Code Playgroud)
那我输了Callable。显然我不能让协议继承自Callable;
class CallableWithAttrs(Callable, Protocol):
attr1: str
attr2: str
Run Code Online (Sandbox Code Playgroud)
mypy 说:
error: Invalid base class "Callable"
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我只使用Callable,我会丢失有关添加属性的信息。
这在引入类型变量时可能更加复杂,即当装饰器必须返回与给定函数相同类型的可调用对象时func,正如 MisterMiyagi 在评论中指出的那样。
import functools
from typing import *
C = TypeVar('C', bound=Callable)
def decorator(func: C) -> C:
func.attr1 = …Run Code Online (Sandbox Code Playgroud)