程式碼自動產生文件¶
在本教學的前一節中,您手動在 Sphinx 中文件化了一個 Python 函數。然而,描述與程式碼本身不同步,因為函數簽名並不相同。此外,能夠重複使用 Python docstring 在文件中,而不是必須在兩個地方寫入資訊,這會很好。
幸運的是,autodoc 擴充功能 提供了此功能。
使用 autodoc 重複使用簽名和 docstring¶
要使用 autodoc,首先將其新增到已啟用擴充功能的清單中
extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
]
接下來,將 .. py:function
指令的內容移動到原始 Python 檔案中的函數 docstring,如下所示
def get_random_ingredients(kind=None):
"""
Return a list of random ingredients as strings.
:param kind: Optional "kind" of ingredients.
:type kind: list[str] or None
:raise lumache.InvalidKindError: If the kind is invalid.
:return: The ingredients list.
:rtype: list[str]
"""
return ["shells", "gorgonzola", "parsley"]
最後,將 Sphinx 文件中的 .. py:function
指令替換為 autofunction
you can use the ``lumache.get_random_ingredients()`` function:
.. autofunction:: lumache.get_random_ingredients
如果您現在建置 HTML 文件,輸出將會相同!優點是它是由程式碼本身產生的。Sphinx 從 docstring 中取得 reStructuredText 並包含進來,同時也產生了正確的交叉參考。
您也可以從其他物件自動產生文件。例如,新增 InvalidKindError
例外的程式碼
class InvalidKindError(Exception):
"""Raised if the kind is invalid."""
pass
並將 .. py:exception
指令替換為 autoexception
,如下所示
or ``"veggies"``. Otherwise, :py:func:`lumache.get_random_ingredients`
will raise an exception.
.. autoexception:: lumache.InvalidKindError
再次強調,在執行 make html
後,輸出將會與之前相同。
產生全面的 API 參考文檔¶
雖然使用 sphinx.ext.autodoc
可以更輕鬆地保持程式碼和文件同步,但它仍然需要您為每個要文件化的物件編寫一個 auto*
指令。Sphinx 提供了更高層級的自動化:autosummary 擴充功能。
autosummary
指令會產生包含所有必要 autodoc
指令的文件。要使用它,首先啟用 autosummary 擴充功能
extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
]
接下來,建立一個新的 api.rst
檔案,內容如下
API
===
.. autosummary::
:toctree: generated
lumache
記得將新文件包含在根 toctree 中
Contents
--------
.. toctree::
usage
api
最後,在您執行 make html
建置 HTML 文件後,它將包含兩個新頁面
api.html
,對應於docs/source/api.rst
,並包含一個表格,其中包含您包含在autosummary
指令中的物件(在本例中,只有一個)。generated/lumache.html
,對應於新建立的 reStructuredText 檔案generated/lumache.rst
,並包含模組成員的摘要,在本例中是一個函數和一個例外。

autosummary 建立的摘要頁面¶
摘要頁面中的每個連結都會將您帶到您最初使用對應 autodoc
指令的位置,在本例中是在 usage.rst
文件中。