我想创建装饰器,它将默认值添加到函数参数,但保留函数签名的参数名称和类型。
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
这可能吗?
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'