Python decorator handling docstrings

前端 未结 3 1819
无人共我
无人共我 2020-11-27 15:44

I have a problem using docstrings with decorators. Given the following example:

def decorator(f):
    def _decorator():
        print \'decorator active\'
           


        
相关标签:
3条回答
  • 2020-11-27 16:26

    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?

    0 讨论(0)
  • 2020-11-27 16:28

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

    0 讨论(0)
  • 2020-11-27 16:43

    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.

    0 讨论(0)
提交回复
热议问题