Python 装饰器处理文档字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1782843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python decorator handling docstrings
提问by Günther Jena
I have a problem using docstrings with decorators. Given the following example:
我在使用带有装饰器的文档字符串时遇到问题。给出以下示例:
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)
Now the help doesn't show me the docstring of foo
as expected, it shows:
现在帮助没有foo
按预期向我显示文档字符串,它显示:
Help on function _decorator in module __main__:
_decorator()
Without the decorator, the help is correct:
没有装饰器,帮助是正确的:
Help on function foo in module __main__:
foo()
the magic foo function
I know, that the function foo
is wrapped by the decorator, and so the function object is not the function foo
any more. But what is a nice solution to get the docstring (and the help) as expected?
我知道,该函数foo
是由装饰器包装的,因此函数对象不再是函数foo
。但是,按预期获取文档字符串(和帮助)的好方法是什么?
回答by P?r Wieslander
Use functools.wraps()
to update the attributes of the decorator:
使用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)
Also see the Standard Library documentationfor functools
.
另请参阅标准库文件的functools
。
回答by Günther Jena
I found a solution, but don't know if it's really nice:
我找到了一个解决方案,但不知道它是否真的很好:
def decorator(f):
def _decorator():
print 'decorator active'
f()
_decorator.__name__=f.__name__
_decorator.__doc__=f.__doc__
return _decorator
The part with _decorator.__name__=f.__name__
seems a little bit hideous... What do you think?
_decorator.__name__=f.__name__
有的部分看起来有点可怕……你怎么看?
回答by Mark Byers
Take a look at functools.wraps
: http://docs.python.org/library/functools.html
看看functools.wraps
:http: //docs.python.org/library/functools.html