如果我执行以下操作

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))?

最佳答案

这是使用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

关于python - 将调用签名复制到装饰器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2982974/

10-12 19:26