簡體   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