繁体   English   中英

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

[英]Including docstring in Sphinx Documentation

我只想在我的 Sphinx 文档中包含特定 function 的文档字符串。 但是,似乎没有选项可以仅显示这些详细信息而无需关联的 class 和 function 定义使用http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html

我已经尝试创建一个 class,如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

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

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

在查看源代码并进行试验后 - 这是在 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 文件中使用以下格式。 只需在您的 objname 前面加上 auto。

.. autosimple:: mod.MyClass.my_method

我在 Sphinx 5.3 中使用了这种方法。

如果您不想覆盖 class API 文档的默认 MethodDocumenter,您还需要覆盖以下can_document_member并将其设置为 False。 生成的 class 如下所示

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 的答案相同。

暂无
暂无

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

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