Python装饰器处理文档
使用docstrings与装饰器有问题。 给出以下示例:
def decorator(f): def _decorator(): print 'decorator active' f() return _decorator @decorator def foo(): '''the magic foo function''' print 'this is function foo' help(foo)  现在的帮助并没有像预期的那样给我显示foo的文档,它显示: 
 Help on function _decorator in module __main__: _decorator() 
没有装饰者,帮助是正确的:
 Help on function foo in module __main__: foo() the magic foo function 
 我知道,函数foo是由装饰器包装的,所以函数对象不再是函数foo了。 但是,如何获得文档string(和帮助)是一个很好的解决scheme? 
 使用functools.wraps()更新装饰器的属性: 
 from functools import wraps def decorator(f): @wraps(f) def _decorator(): print 'decorator active' f() return _decorator @decorator def foo(): '''the magic foo function''' print 'this is function foo' help(foo) 
 另请参阅functools的标准库文档 。 
我find了一个解决scheme,但不知道它是否真的很好:
 def decorator(f): def _decorator(): print 'decorator active' f() _decorator.__name__=f.__name__ _decorator.__doc__=f.__doc__ return _decorator 
 具有_decorator.__name__=f.__name__似乎有点可怕…您怎么看? 
 看看functools.wraps : http : //docs.python.org/library/functools.html 
 现在可能有点老了,但这是你如何做到的。 只要确保@decorator与def decorator(f)在同一行缩进: 
 from functools import wraps def decorator(f): @wraps(f) def _decorator(): print 'decorator active' return f() return _decorator @decorator def foo(): '''the magic foo function''' print 'this is function foo' help(foo)