7.3. API手册制作指南#

从代码中根据注释来生成的文档的方式有多种, 但是借助于为文档构建而设计的Sphinx及其技术生态, sphinx-apidoc 工具无疑是其中功能最强大,也最方便的一个。

注解

sphinx-apidoc 工具的作用是从代码中提取文字内容而生成文档, 需要进一步借助 Sphinx 工具来构建结果。

7.3.1. 一个例子#

撰写代码和文档#

要用 sphinx-apidoc 来提取文件,首先得有一份注释良好的源代码。 在文字内容提取方面,主要有两种场景。

一种是没有文档项目的情况下直接从头构建; 另外一种是在已有文档项目的基础上添加API文档。

第一种相对简单,这里以第二种场景为例进行说明。

初始化Sphinx工程#

  1. 在源码根目录, 新建 docs 文件夹, 进入该文件夹

  2. 终端输入: sphinx-quickstart 启动Sphinx

  3. 设置项目名称为 PyTool , 作者名, 工程发布版本(Project release)等

  4. 设置项目文档语言等, 类似如下

配置Sphinx工程#

  1. 添加库路径.

打开 source/conf.py 文件, 可以看到:

# If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath(‘.’))

因而在 conf.py 中添加 sys.path.insert(0, os.path.abspath('../../'))

提示

路径非常重要,在构建过程中需要读取源代码(甚至运行)。 必须配置好以避免找不到Python模块的情况。 如果生成的HTML文档中没有注释, 只有包名, 那么很有可能是没找到包, 可参见问题解决部分.

生成API注释文档#

本部分使用 sphinx-apidoc 命令自动从代码中提取注释并生成 rst 文件.

回退到源码工程目录, 终端执行命令: sphinx-apidoc -o ./docs/source/ ./ 将在 source 文件夹创建各模块的注释文档( .rst 格式).

编译生成API手册#

接着打开 index.rst 文件, 在其中添加 module.rst 文件, 如下:

Welcome to PyTool's documentation!
==================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

可以随意打开一个模块的 rst 文件, 如下:

pytool.file package
===================

Submodules
----------

pytool.file.binfile module
--------------------------

.. automodule:: pytool.file.binfile
    :members:
    :undoc-members:
    :show-inheritance:

pytool.file.copy module
-----------------------

.. automodule:: pytool.file.copy
    :members:
    :undoc-members:
    :show-inheritance:

可以看到文件中并没有注释, 那么怎么生成文档呢? 原来是在 build 时, Sphinx才提取文档注释, 生成文档.

提示

生成的模块的 rst 文件中的 .. automodule:: 用于自动抽取文档注释.

然后像构建普通文档一样编译即可. 当然你还可以修改 conf.py 文件, 以修改文档主题等等.

生成的文档示例如下图所示:

no module error

图 7.3.1 自动生成的文档示例#

使用Sphinx自动从PyML包中的注释, 提取并生成文档, 注释可以使用reStructedText语言撰写.

7.3.2. 文档注释风格支持#

有两种:

  • Google风格

  • NumPy风格

如果代码中包含两种风格的注释, 可以在 conf.py 中的 extensions 处添加扩展 sphinx.ext.napoleon 即可.

7.3.3. 问题解决#

生成的文档无注释#

如果你生成的html文档中没有注释, 只有包名, 那么很有可能是没找到包, 或者 代码中用到的库没有装. 在 conf.py 中添加 sys.path.insert(0, os.path.abspath('../../')) 设置好路径, 并安装缺失的相应模块即可.

no module error

图 7.3.2 no module error reported by Sphinx#

注释中不显示公式#

在注释起始符前加 r , 如:

r"""Computes tanh of `x` element-wise.

 Specifically, :math:`y = {\rm tanh}(x) = {{e^{2x} - 1} \over {e^{2x} + 1}}`.

 Arguments:
     x {lists or array} -- inputs

 Returns:
     array -- outputs

 """