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

2024-06-01 08:49:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Sphinx来记录我用Python编写的一些代码。我在我的项目中使用了stuartgathman的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

Tags: 函数代码nameselfremessagesearchsphinx
1条回答
网友
1楼 · 发布于 2024-06-01 08:49:46

你可以用这个:

import functools

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

header = functools.wraps(header)(Milter.noreply(header))

要举例说明这是在做什么,请考虑这个decorator和函数:

^{pr2}$

decorator只是返回函数的可调用函数,因此可以使用函数作为参数调用decorator,然后调用结果:

>>> dec(f)
<function wrap at 0x10909e758>
>>> dec(f)()
hey

但正如您所注意到的,问题在于__doc__和{}变量没有被保留,因为decorator没有使用functools.wraps

>>> f.__doc__
'docstring'
>>> dec(f).__doc__
>>>

所以,既然您不能修改原始的decorator定义,就自己打包吧:

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

您还可以定义自己的decorator,它以decorator作为参数,并正确地包装函数。在

相关问题 更多 >