63

我在使用带有装饰器的文档字符串时遇到问题。给定以下示例:

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按预期向我显示文档字符串,它显示:

Help on function _decorator in module __main__:

_decorator()

没有装饰器,帮助是正确的:

Help on function foo in module __main__:

foo()
    the magic foo function

我知道,函数foo是由装饰器包装的,所以函数对象不再是函数foo。但是,按预期获取文档字符串(和帮助)的好解决方案是什么?

4

4 回答 4

102

用于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)

另请参阅functools.

于 2009-11-23T12:33:04.830 回答
22

我找到了一个解决方案,但不知道它是否真的很好:

def decorator(f):
    def _decorator():
        print 'decorator active'
        f()
    _decorator.__name__=f.__name__
    _decorator.__doc__=f.__doc__
    return _decorator

的部分_decorator.__name__=f.__name__似乎有点可怕......你觉得呢?

于 2009-11-23T12:31:32.057 回答
4

看看functools.wrapshttp ://docs.python.org/library/functools.html

于 2009-11-23T12:34:52.050 回答
0

解决方案非常简单。文档字符串应该在主函数顶部调用的最顶层装饰器中提及。找到下面的例子:

import math

def wrap2(func):
    def squarer(x):
        return [math.sqrt(i) for i in func(x)]
    return squarer
    

def wrap1(func):
    def summer(x):
        return [i*2 for i in func(x)]
    return summer

def wrap3(func):
    def rounder(x):
        return [round(i,1) for i in func(x)]
    return rounder

def wrap4(func):
    def stringer(x):
        '''
    Enter the input of a 2-dim array to get the output
    '''
        return [str(i)+' rounds ' for i in func(x)]
    return stringer

@wrap4
@wrap3
@wrap2
@wrap1
def rooter(i):
    return [sum(p) for p in i]

help(rooter)

# output
Help on function stringer in module __main__:

stringer(x)
    Enter the input of a 2-dim array to get the output

- -或者 - -

Signature: rooter(x)
Docstring: Enter the input of a 2-dim array to get the output
File:      d:\<ipython-input-392-487fc73b05cf>
Type:      function

因此,必须在wrap4 装饰器函数中提及 Doc String以使其在主函数中可见。

于 2021-12-10T13:08:17.560 回答