相关疑难解决方法(0)

Python 3类型提示装饰器

请考虑以下代码:

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)

python typing decorator type-hinting python-3.x

18
推荐指数
2
解决办法
3684
查看次数

标签 统计

decorator ×1

python ×1

python-3.x ×1

type-hinting ×1

typing ×1