Search code examples
pythondecoratordocstring

Python decorator handling docstrings


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?


Solution

  • 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.