我有一個基礎裝飾器,它需要參數,但也是由其他裝飾器構建的。我似乎無法確定在哪裏放置functools.wraps以保留裝飾函數的完整簽名。將functools.wraps應用到嵌套包裝
import inspect
from functools import wraps
# Base decorator
def _process_arguments(func, *indices):
""" Apply the pre-processing function to each selected parameter """
@wraps(func)
def wrap(f):
@wraps(f)
def wrapped_f(*args):
params = inspect.getargspec(f)[0]
args_out = list()
for ind, arg in enumerate(args):
if ind in indices:
args_out.append(func(arg))
else:
args_out.append(arg)
return f(*args_out)
return wrapped_f
return wrap
# Function that will be used to process each parameter
def double(x):
return x * 2
# Decorator called by end user
def double_selected(*args):
return _process_arguments(double, *args)
# End-user's function
@double_selected(2, 0)
def say_hello(a1, a2, a3):
""" doc string for say_hello """
print('{} {} {}'.format(a1, a2, a3))
say_hello('say', 'hello', 'arguments')
這段代碼的結果應該是是:
saysay hello argumentsarguments
但是,在運行上say_hello幫助給了我:
say_hello(*args, **kwargs)
doc string for say_hello
一切都被保留,除參數名稱。
看來我只需要在某處添加另一個@wraps(),但是在哪裏呢?
你使用python 2或Python 3? – bravosierra99