我正在尝试编写像这样带有附加参数的装饰器
def dec(arg):
def modifier(cls) -> cls:
# modify cls
return cls;
pass
return modifier
pass
@dec(63)
class X:
a: int = 47;
pass
这当然是错误,因为 cls
没有定义。
我试过 dec(arg: int) -> Callable[[type], type]
和 modifier(cls: type) -> type
但这会弄乱 IntelliSense (vscode) (写 X.
不再提供 a
)
回答1
使用 https://docs.python.org/3/library/typing.html#typing.TypeVar 定义可用于注释函数的泛型类型。使用 https://docs.python.org/3/library/typing.html#typing.Type 来注释函数接受并返回 TypeVar 的类型/类
from typing import TypeVar, Type
T = TypeVar('T')
def dec(arg):
def modifier(cls: Type[T]) -> Type[T]:
# modify cls
return cls
return modifier
@dec(63)
class X:
a: int = 47