繁体   English   中英

当一个方法中有两个装饰器时,为什么sphinx autodoc输出装饰器的文档字符串?

[英]Why does sphinx autodoc output a decorator's docstring when there are two decorators in a method?

我想使用sphinx autodoc为具有@classproperty@classmethod装饰器的方法生成文档。 我得到了@classmethod的文档,而不是方法的文档。 如果删除任何装饰器,则一切正常。 类代码的结构如下:

class Example(object):
    @classproperty
    @classmethod
    def example_method(cls):
       """Method description"""
       pass

类属性装饰器:

class classproperty(property):
    def __get__(self, obj, type=None):
        return self.fget.__get__(None, type)()

我正在使用生成文档:

.. autoclass:: Example
    :members:

Sphinx文档中

注意

如果要记录修饰的函数或方法,请记住,自动文档通过导入模块并检查给定函数或方法的doc属性来检索其文档字符串。 这意味着,如果装饰器将装饰的功能替换为另一个,则必须将原始文档复制到新功能。

从Python 2.5开始,functools.wraps()可用于创建行为良好的装饰函数。

因此,我认为这里的问题是装饰器在包装函数时会丢弃docstring。 wraps应该能够帮助您。

您可以遵循该主题的Python文档中的模式。 对于您的用例,您可以这样做:

from functools import wraps

def classpropertymethod(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        return classproperty(classmethod(f(*args, **kwargs)))
    return wrapper

@classpropertymethod
def example_method(cls):
    """Method description"""
    pass

这将从正确传递的example_method获取文档字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM