代码自动生成文档

在本教程的上一节中,您手动在 Sphinx 中记录了一个 Python 函数。但是,描述与代码本身不同步,因为函数签名不相同。此外,最好在文档中重用 Python 文档字符串,而不是必须在两个地方编写信息。

幸运的是,autodoc 扩展提供了此功能。

使用 autodoc 重用签名和文档字符串

要使用 autodoc,首先将其添加到已启用扩展的列表中

docs/source/conf.py
extensions = [
    'sphinx.ext.duration',
    'sphinx.ext.doctest',
    'sphinx.ext.autodoc',
]

接下来,将 .. py:function 指令的内容移动到原始 Python 文件中的函数文档字符串,如下所示

lumache.py
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

docs/source/usage.rst
you can use the ``lumache.get_random_ingredients()`` function:

.. autofunction:: lumache.get_random_ingredients

如果您现在构建 HTML 文档,输出将是相同的! 优势在于它是从代码本身生成的。 Sphinx 从文档字符串中获取了 reStructuredText 并将其包含在内,还生成了正确的交叉引用。

您还可以从其他对象自动生成文档。 例如,添加 InvalidKindError 异常的代码

lumache.py
class InvalidKindError(Exception):
    """Raised if the kind is invalid."""
    pass

并将 .. py:exception 指令替换为 autoexception,如下所示

docs/source/usage.rst
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 扩展

docs/source/conf.py
extensions = [
   'sphinx.ext.duration',
   'sphinx.ext.doctest',
   'sphinx.ext.autodoc',
   'sphinx.ext.autosummary',
]

接下来,创建一个新的 api.rst 文件,其中包含以下内容

docs/source/api.rst
API
===

.. autosummary::
   :toctree: generated

   lumache

记住将新文档包含在根 toctree 中

docs/source/index.rst
Contents
--------

.. toctree::

   usage
   api

最后,在您运行 make html 构建 HTML 文档后,它将包含两个新页面

  • api.html,对应于 docs/source/api.rst,并包含一个表格,其中包含您包含在 autosummary 指令中的对象(在本例中,只有一个)。

  • generated/lumache.html,对应于新创建的 reStructuredText 文件 generated/lumache.rst,并包含模块成员的摘要,在本例中为一个函数和一个异常。

Summary page created by autosummary

autosummary 创建的摘要页面

摘要页面中的每个链接都将带您到最初使用相应 autodoc 指令的位置,在本例中是在 usage.rst 文档中。

注意

生成的文件基于 Jinja2 模板,这些模板可以自定义,但这超出了本教程的范围。