Python装饰器处理文档字符串 [英] Python decorator handling docstrings
本文介绍了Python装饰器处理文档字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用带装饰符的文档字符串时遇到问题。给出以下示例:
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)
现在,该帮助并未像预期的那样显示 foo
的文档字符串,而是显示了:
Now the help doesn't show me the docstring of foo
as expected, it shows:
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
我知道,该函数 foo
由装饰器包装,因此函数对象不再是函数 foo
。但是,按预期方式获得文档字符串(和帮助)的最佳解决方案是什么?
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?
推荐答案
使用 functools.wraps()
更新装饰器的属性:
Use functools.wraps()
to update the attributes of the decorator:
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
。
这篇关于Python装饰器处理文档字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文