如果我执行以下操作
def mydecorator(f):
def wrapper(*args, **kwargs):
f(*args, **kwargs)
wrapper.__doc__ = f.__doc__
wrapper.__name__ = f.__name__
return wrapper
@mydecorator
def myfunction(a,b,c):
'''My docstring'''
pass
然后输入help myfunction
,我得到:
Help on function myfunction in module __main__:
myfunction(*args, **kwargs)
My docstring
因此,名称和文档字符串被正确复制。有没有办法复制实际的呼叫签名,在这种情况下(a, b, c)
?
答案 0 :(得分:9)
以下是使用Michele Simionato的decorator module修复签名的示例:
import decorator
@decorator.decorator
def mydecorator(f,*args, **kwargs):
return f(*args, **kwargs)
@mydecorator
def myfunction(a,b,c):
'''My docstring'''
pass
help(myfunction)
# Help on function myfunction in module __main__:
# myfunction(a, b, c)
# My docstring
答案 1 :(得分:3)
尝试decorator
模块,可在此处获取:http://pypi.python.org/pypi/decorator/3.2.0
文档的相关部分:http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem
答案 2 :(得分:1)
此功能由Python标准库inspect module提供,特别是由inspect.getargspec提供。
>>> import inspect
>>> def f(a, b, c=0, *args, **kwargs): return
...
>>> inspect.getargspec(f)
ArgSpec(args=['a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(0,))