向修饰函数添加默认值并更新类型签名

问题描述 投票:0回答:1

我想创建装饰器,它将默认值添加到函数参数,但保留函数签名的参数名称和类型。

from typing import Callable

def optional[**P](f: Callable[P, None]) -> Callable[P, None]:
    def wrapper(*args: P.args, **kwargs: P.kwargs):
        ...

    return wrapper

@optional
def my_func(a: str, b: int):
    ...

my_func("a")  # ERROR: b also expected

这可能吗?

python decorator typing
1个回答
0
投票

也许我遗漏了一些东西,但你可以使用

functools.wraps

from functools import wraps
from typing import Callable


def optional(f: Callable) -> Callable:
    @wraps(f)
    def wrapper(*args, **kwargs):
        f(*args, **kwargs)

    return wrapper


@optional
def my_func(a: str, b: int):
    pass


print(f"{my_func=}")
print(f"{my_func.__annotations__=}")

my_func("a")  # ERROR: b also expected

打印:

my_func=<function my_func at 0x7fab7180fba0>
my_func.__annotations__={'a': <class 'str'>, 'b': <class 'int'>}

...
TypeError: my_func() missing 1 required positional argument: 'b'
© www.soinside.com 2019 - 2024. All rights reserved.