从代码自动生成文档¶
在本教程的 上一节 中,您在 Sphinx 中手动记录了一个 Python 函数。然而,描述与代码本身不同步,因为函数签名并不相同。此外,在文档中重用 Python 文档字符串 会更好,而不是必须在两个地方编写信息。
幸运的是,autodoc 扩展 提供了此功能。
使用 autodoc 重用签名和文档字符串¶
使用 autodoc,首先将其添加到已启用的扩展列表中:
extensions = [
'sphinx.ext.duration',
'sphinx.ext.doctest',
'sphinx.ext.autodoc',
]
接下来,将 .. py:function 指令的内容移动到原始 Python 文件中的函数文档字符串中,如下所示:
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"]
最后,用 autofunction 替换 Sphinx 文档中的 .. py:function 指令:
you can use the ``lumache.get_random_ingredients()`` function:
.. autofunction:: lumache.get_random_ingredients
如果您现在构建HTML文档,输出将是相同的!优点是它是从代码本身生成的。Sphinx 从文档字符串中获取 reStructuredText 并将其包含在内,还生成了适当的交叉引用。
您还可以从其他对象自动生成文档。例如,添加 InvalidKindError 异常的代码:
class InvalidKindError(Exception):
"""Raised if the kind is invalid."""
pass
并用 autoexception 替换 .. py:exception 指令,如下所示:
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 指令,首先启用 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 文档。
备注
生成的文件基于 Jinja2 templates,其可以 自定义,但这超出了本教程的范围。