从代码自动生成文档¶
在本教程的上一节中,你手动在 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"]
最后,将 Sphinx 文档中的 .. py:function 指令替换为 autofunction
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
并将 .. 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 文档。