Python Sphinx autodoc和装饰成员

2024-09-27 09:30:16 发布

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

我试图使用Sphinx来记录我的Python类。我使用autodoc:

.. autoclass:: Bus
   :members:

虽然它正确地获取了我的方法的docstring,但是那些被修饰的方法:

    @checkStale
    def open(self):
        """
        Some docs.
        """
        # Code

@checkStale存在

def checkStale(f):
    @wraps(f)
    def newf(self, *args, **kwargs):
        if self._stale:
            raise Exception
        return f(self, *args, **kwargs)
    return newf

原型不正确,例如open(*args, **kwargs)

我该怎么解决?我的印象是使用@wraps可以解决这类问题。


Tags: 方法selfreturndefsphinx记录argsopen
3条回答

我对芹菜@task decorator也有同样的问题。

您还可以通过向rst文件中添加正确的函数签名来解决此问题,如下所示:

.. autoclass:: Bus
    :members:

    .. automethod:: open(self)
    .. automethod:: some_other_method(self, param1, param2)

它仍然会自动记录非decorator成员。

sphinx文档在http://www.sphinx-doc.org/en/master/ext/autodoc.html#directive-automodule中提到了这一点——搜索“如果方法的签名被装饰器隐藏,则此选项非常有用。”

在我的例子中,我必须使用autofunction在django应用程序的tasks.py模块中指定芹菜任务的签名:

.. automodule:: django_app.tasks
    :members:
    :undoc-members:
    :show-inheritance:

    .. autofunction:: funct1(user_id)
    .. autofunction:: func2(iterations)

要展开我的评论:

Have you tried using the decorator package and putting @decorator on checkStale? I had a similar issue using epydoc with a decorated function.

正如您在评论中所问的,decorator包不是标准库的一部分。

您可以使用如下代码(未经测试):

try:
    from decorator import decorator
except ImportError:
    # No decorator package available. Create a no-op "decorator".
    def decorator(f):
        return f

添加到版本1.1中,现在可以通过在docstring的第一行提供自定义值来重写方法签名。

http://sphinx-doc.org/ext/autodoc.html#confval-autodoc_docstring_signature

@checkStale
def open(self):
    """
    open()
    Some docs.
    """
    # Code

相关问题 更多 >

    热门问题