请考虑以下代码:
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
Run Code Online (Sandbox Code Playgroud)
这段代码按预期工作.现在想象一下我想扩展这个,而不是只是执行func(*args, **kwargs)我想在参数中注入用户名.因此,我修改了函数签名.
from typing import Callable, Any
TFunc = Callable[..., Any] …Run Code Online (Sandbox Code Playgroud)