考虑以下代码:
from typing import Callable, Any
TFunc = Callable[..., Any]
def get_authenticated_user(): return "John"
def require_auth() -> Callable[TFunc, TFunc]:
def decorator(func: TFunc) -> TFunc:
def wrapper(*args, **kwargs) -> Any:
user = get_authenticated_user()
if user is None:
raise Exception("Don't!")
return func(*args, **kwargs)
return wrapper
return decorator
@require_auth()
def foo(a: int) -> bool:
return bool(a % 2)
foo(2) # Type check OK
foo("no!") # Type check failing as intended
这段代码按预期工作。现在想象一下我想扩展它,而不是只执行func(*args, **kwargs)
我想在参数中注入用户名。因此,我修改了函数签名。
from typing import Callable, Any
TFunc = Callable[..., Any]
def get_authenticated_user(): return "John"
def inject_user() -> Callable[TFunc, TFunc]:
def decorator(func: TFunc) -> TFunc:
def wrapper(*args, **kwargs) -> Any:
user = get_authenticated_user()
if user is None:
raise Exception("Don't!")
return func(*args, user, **kwargs) # <- call signature modified
return wrapper
return decorator
@inject_user()
def foo(a: int, username: str) -> bool:
print(username)
return bool(a % 2)
foo(2) # Type check OK
foo("no!") # Type check OK <---- UNEXPECTED
我无法找到一种正确的输入法。我知道在这个例子中,装饰函数和返回函数在技术上应该具有相同的签名(但即使没有检测到)。
答案 0 :(得分:9)
您不能使用Callable
来说明其他参数;它们不是通用的。您唯一的选择就是说您的装饰师需要Callable
并且返回不同的Callable
。
在你的情况下,可以使用typevar
确定返回类型RT = TypeVar('RT') # return type
def inject_user() -> Callable[[Callable[..., RT]], Callable[..., RT]]:
def decorator(func: Callable[..., RT]) -> Callable[..., RT]:
def wrapper(*args, **kwargs) -> RT:
# ...
即使这样,当您使用foo()
时,生成的装饰def (*Any, **Any) -> builtins.bool*
函数的输入签名为reveal_type()
。
目前正在讨论各种提案,以使Callable
更具灵活性,但尚未取得成果。见
Callable
to be able to specify argument names and kinds 举个例子。该列表中的最后一个是一张伞票,其中包含您的特定用例,即改变可调用签名的装饰器:
使用返回类型或使用参数
进行混乱对于任意功能,你根本无法做到这一点 - 甚至没有语法。我在这里为它编写了一些语法。
答案 1 :(得分:2)
PEP 612 在接受答案后被接受,我们现在在 Python 3.10 中有 typing.ParamSpec
和 typing.Concatenate
。有了这些变量,我们就可以正确键入一些操纵位置参数的装饰器。
请注意,mypy 对 PEP 612 的支持仍在进行中 (tracking issue)。
有问题的代码可以这样输入(尽管由于上述原因未在 mypy 上进行测试)
from typing import Callable, ParamSpec, Concatenate, TypeVar
Param = ParamSpec("Param")
RetType = TypeVar("RetType")
OriginalFunc = Callable[Param, RetType]
DecoratedFunc = Callable[Concatenate[Param, str], RetType]
def get_authenticated_user(): return "John"
def inject_user() -> Callable[[OriginalFunc], DecoratedFunc]:
def decorator(func: OriginalFunc) -> DecoratedFunc:
def wrapper(*args, **kwargs) -> RetType:
user = get_authenticated_user()
if user is None:
raise Exception("Don't!")
return func(*args, user, **kwargs) # <- call signature modified
return wrapper
return decorator
@inject_user()
def foo(a: int, username: str) -> bool:
print(username)
return bool(a % 2)
foo(2) # Type check OK
foo("no!") # Type check should fail