在Sphinx文档中包含文档字符串

9 投票
2 回答
3947 浏览
提问于 2025-04-17 04:38

我想在我的Sphinx文档中只包含某个特定函数的文档字符串(docstring)。不过,似乎没有选项可以仅显示这些信息,而不显示相关的类和函数定义,具体可以参考这个链接:http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html

我试着按照这个链接的说明创建一个类:Show *only* docstring in Sphinx documentation?,但我不太确定这和模板的关系是什么。

我也尝试过使用autodoc-process-docstring事件处理器,但没有成功。

所以,我希望我的文档显示的内容(目前是这样的):

class module.MyClass(param)

    This is the class doc string

    my_method()

        This is my method doc string

我只想显示:

This is my method doc string

我当前在.txt文件中的模板是:

.. autoclass:: module.MyClass
    :members: my_method

2 个回答

0

我在使用Sphinx 5.3的时候采用了这种方法。

如果你不想覆盖你类的API文档中的默认方法文档生成器,你还需要覆盖以下这个 can_document_member 并将它设置为False。最终的类看起来如下:

class SimpleDocumenter(autodoc.MethodDocumenter):
"""
Reference a class or method docstring only.
see https://stackoverflow.com/a/7832437/5726546
"""
  objtype = "simple"

    content_indent = ""

    @classmethod
    def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
        return False

    # do not add a header to the docstring
    def add_directive_header(self, sig: str) -> None:
        pass

设置和指令与geographika的回答中的内容是一样的。

15

经过查看源代码和一些实验,这里是如何在 Sphinx 1.1 中实现的。

在你的 conf.py 文件中,创建一个新的 MethodDocumenter 子类。在这里,你可以设置一个新的 "objtype",确保文档字符串没有缩进,并且去掉标题。

from sphinx.ext import autodoc

class SimpleDocumenter(autodoc.MethodDocumenter):
    objtype = "simple"

    #do not indent the content
    content_indent = ""

    #do not add a header to the docstring
    def add_directive_header(self, sig):
        pass

然后,确保通过以下函数将其添加到可用的文档生成器中(同样在 conf.py 中):

def setup(app):
    app.add_autodocumenter(SimpleDocumenter)

接下来,当你只想显示一个方法的文档字符串时,可以在你的 .txt 或 .rst 文件中使用以下格式。只需在你的对象名称前加上 auto。

.. autosimple:: mod.MyClass.my_method

撰写回答