Python decorator handling docstrings

此生再无相见时 提交于 2019-11-26 09:29:45

问题


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:

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?


回答1:


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)

Also see the Standard Library documentation for functools.




回答2:


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?




回答3:


Take a look at functools.wraps: http://docs.python.org/library/functools.html



来源:https://stackoverflow.com/questions/1782843/python-decorator-handling-docstrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!