python - 将 Sphinx 与 reStructuredText 格式的文档字符串结合使用

标签 python python-sphinx restructuredtext docstring

根据writing docstrings tutorial Sphinx 中,可以利用 Sphinx 的 autodoc 扩展来自动生成文档。我们可以使用 Sphinx 格式、GoogleNumpy 编写文档字符串(后两者带有 napoleon 扩展名) .

是否可以以 reStructuredText 格式编写文档字符串?

例如:

"""[Summary]

Extended description of function.

:param int arg1: Description of arg1.
:param str arg2: Description of arg2.
:raise: ValueError if arg1 is equal to arg2
:return: Description of return value
:rtype: bool
"""

为了比较,这是 Sphinx 原生格式:

"""[Summary]

:param [ParamName]: [ParamDescription], defaults to [DefaultParamVal]
:type [ParamName]: [ParamType](, optional)
...
:raises [ErrorType]: [ErrorDescription]
...
:return: [ReturnDescription]
:rtype: [ReturnType]
"""

Comparison of docstrings

最佳答案

这两种格式实际上是相同的。这可能会令人困惑,但是所谓的 Info field lists可以被认为是 reST 文档字符串语法。如果您仔细查看版本号,它从 Sphinx 0.4 版本开始就存在,接下来我们查看 current Sphinx change list它发送至change list that predates version 1.0 ...最早提到的是:

Release 0.4 (Jun 23, 2008)

==========================

  • Sphinx now interprets field lists with fields like :param foo: in description units.

如果我们想进一步挖掘 reST 文档字符串语法的定义,请查看 Doc-SIG - Python Documentation Special Interest Group 的文件。将是要走的路,但 PEP 256 - Rationale 给出了足够好的概述。日期为 2001 年 6 月 1 日。当时出现的、被最常引用的文件仅提出了一个松散的建议:

PEP 257 -- Docstring Conventions

Python is case sensitive and the argument names can be used for keyword arguments, so the docstring should document the correct argument names. It is best to list each argument on a separate line.

总而言之,reST 文档字符串语法仅包含使用 reST Field Lists !(NumPy 和 Google 风格只是编写 reST 字段列表的不同风格)!

Field List - reStructuredText Markup Specification

Field lists are mappings from field names to field bodies,

(...)

The interpretation of individual words in a multi-word field name is up to the application. The application may specify a syntax for the field name.

Syntax diagram (simplified):

+--------------------+----------------------+
| ":" field name ":" | field body           |
+-------+------------+                      |
        | (body elements)+                  |
        +-----------------------------------+

由应用程序指定字段名称的语法;因此,Sphinx 文档生成器为问题中的 2 个示例语法指定的是它们是等效的(如果您更改为不同的文档生成器,则这不一定成立)。

关于python - 将 Sphinx 与 reStructuredText 格式的文档字符串结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71249750/

相关文章:

python - IO错误: [Errno 2] No such file or directory: (Python: I am having this error even though the file does exist)

python - 在 strip 中创建卡的异常

python - 使用 python 连接到 Hbase 失败

python-sphinx - 是否可以用另一个指令替换一个指令

python - 使用sphinx处理字符串

javascript - Sphinx 和 JavaScript 文档工作流

git - 如何从 readthedocs 站点提供静态非图像 Assets ?

python - 加快Python中wav的读取速度

python - 如何强制 Sphinx 使用 Python 3.x 解释器

html - 将 CSS 类添加到 RST 中的链接