Python 斯芬克斯和装饰师,我';我无法修改

Python 斯芬克斯和装饰师,我';我无法修改,python,python-sphinx,Python,Python Sphinx,我正在使用Sphinx来记录我用Python编写的一些代码。我在项目中使用了Stuart Gathman的pymilter库,因此我的许多函数都经过了修饰。我在这里看到了关于修饰函数和Sphinx的问题,但它们不适用于我,因为我无法修改milter库代码 关于如何在不必重写斯芬克斯文档的情况下解决这个问题的想法将非常棒 谢谢 @Milter.noreply def header( self, name, hval ): """ Processes headers from the

我正在使用Sphinx来记录我用Python编写的一些代码。我在项目中使用了Stuart Gathman的pymilter库,因此我的许多函数都经过了修饰。我在这里看到了关于修饰函数和Sphinx的问题,但它们不适用于我,因为我无法修改milter库代码

关于如何在不必重写斯芬克斯文档的情况下解决这个问题的想法将非常棒

谢谢

@Milter.noreply
def header( self, name, hval ):
    """
    Processes headers from the incoming message and writes them to a new variable for database storage.
    """
    rgxSubject = re.compile( '^(subject)', re.IGNORECASE | re.DOTALL )
    rgxMessageID = re.compile( '^(message-id)', re.IGNORECASE | re.DOTALL )


    self.fp.write( "%s: %s\n" % ( name, hval ) )
    self.headers.append( "%s: %s\n" % ( name, hval ) )

    if ( rgxSubject.search( name ) ) or ( rgxMessageID.search( name ) ):
        self.log.info( "%s: %s" % ( name, hval ) )
        self.subjMsgId[name] = hval
        if ( rgxSubject.search( name ) ): self.Subject = hval

    return Milter.CONTINUE
你可以用这个:

import functools

def header( self, name, hval ):
   pass
   # ...

header = functools.wraps(header)(Milter.noreply(header))
要给出一个这样做的示例,请考虑以下装饰器和函数:

>>> def dec(f):
...    def wrap():
...       return f()
...    return wrap
... 
>>> 
>>> def f():
...    """docstring"""
...    print 'hey'
decorator只是返回函数的可调用函数,因此您可以将函数作为参数调用decorator,然后调用结果:

>>> dec(f)
<function wrap at 0x10909e758>
>>> dec(f)()
hey
因此,既然您不能修改最初的decorator定义,只需自己将其包装起来:

>>> functools.wraps(f)(dec(f))()
hey
>>> functools.wraps(f)(dec(f)).__doc__
'docstring'
您还可以定义自己的decorator,该decorator将decorator作为参数并正确封装函数

>>> functools.wraps(f)(dec(f))()
hey
>>> functools.wraps(f)(dec(f)).__doc__
'docstring'