sphinx.ext.napoleon – 支持NumPy和Google风格的文档字符串¶
模块作者: Rob Ruana
Added in version 1.3.
概述¶
您是否厌倦了写这样的文档字符串:
:param path: The path of the file to wrap
:type path: str
:param field_storage: The :class:`FileStorage` instance to wrap
:type field_storage: FileStorage
:param temporary: Whether or not to delete the file when the File
instance is destructed
:type temporary: bool
:returns: A buffered writable file descriptor
:rtype: BufferedFileStorage
reStructuredText is great, but it creates visually dense, hard to read docstrings. Compare the jumble above to the same thing rewritten according to the Google Python Style Guide:
Args:
path (str): The path of the file to wrap
field_storage (FileStorage): The :class:`FileStorage` instance to wrap
temporary (bool): Whether or not to delete the file when the File
instance is destructed
Returns:
BufferedFileStorage: A buffered writable file descriptor
可读性更强,不是吗?
拿破仑是一个 扩展 ,使 Sphinx 能够解析 NumPy 和 Google 风格的文档字符串 - 这是 Khan Academy 推荐的风格.
Napoleon 是一个预处理器,它解析 NumPy 和 Google 风格的文档字符串,并在 Sphinx 尝试解析之前将它们转换为 reStructuredText.这是在 Sphinx 处理文档过程中发生的一个中间步骤,因此它不会修改你实际源代码文件中的任何文档字符串.
开始使用¶
在 :doc :设置 Sphinx </usage/quickstart> 以构建文档之后,在 Sphinx 的
conf.py文件中启用 napoleon:# conf.py # Add napoleon to the extensions list extensions = ['sphinx.ext.napoleon']
使用
sphinx-apidoc来构建你的 API 文档:$ sphinx-apidoc -f -o docs/source projectdir
文档字符串¶
拿破仑解释每个 autodoc 可以找到的文档字符串,包括 模块 、 类 、 属性 、 方法 、 函数 和 变量 上的文档字符串.在每个文档字符串内部,特殊格式的 Sections 被解析并转换为 reStructuredText.
所有标准的 reStructuredText 格式仍然按预期工作.
文档字符串部分¶
以下所有章节标题均受支持:
Args(alias of Parameters)Arguments(alias of Parameters)AttentionAttributesCautionDangerErrorExampleExamplesHintImportantKeyword Args(alias of Keyword Arguments)Keyword ArgumentsMethodsNoteNotesOther ParametersParametersReturn(alias of Returns)ReturnsRaise(alias of Raises)RaisesReferencesSee AlsoTipTodoWarningWarnings(alias of Warning)Warn(alias of Warns)WarnsYield(alias of Yields)Yields
Google 与 NumPy¶
Napoleon 支持两种文档字符串样式: Google 和 NumPy .这两种样式的主要区别在于:Google 使用缩进来分隔部分,而 NumPy 使用下划线.
Google 样式:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Args:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
Returns:
bool: Description of return value
"""
return True
NumPy 风格:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
"""
return True
NumPy 风格通常需要更多的垂直空间,而 Google 风格则更倾向于使用更多的水平空间.Google 风格在处理短小简单的文档字符串时通常更易于阅读,而 NumPy 风格在处理较长且深入的文档字符串时更易于阅读.
选择样式大多是出于美学考量,但这两种样式不应混合.为你的项目选择一种样式,并保持一致.
参见
完整示例:
示例_谷歌
示例_numpy
类型注解¶
PEP 484 引入了一种在 Python 代码中表达类型的标准方法.这是直接在文档字符串中表达类型的替代方案.根据 PEP 484 表达类型的一个好处是类型检查器和集成开发环境(IDEs)可以利用它们进行静态代码分析. PEP 484 后来被 PEP 526 扩展,后者引入了一种相似的方式来注解变量(和属性).
Google风格与Python 3类型注释:
def func(arg1: int, arg2: str) -> bool:
"""Summary line.
Extended description of function.
Args:
arg1: Description of arg1
arg2: Description of arg2
Returns:
Description of return value
"""
return True
class Class:
"""Summary line.
Extended description of class
Attributes:
attr1: Description of attr1
attr2: Description of attr2
"""
attr1: int
attr2: str
Google样式的文档字符串中的类型:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Args:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
Returns:
bool: Description of return value
"""
return True
class Class:
"""Summary line.
Extended description of class
Attributes:
attr1 (int): Description of attr1
attr2 (str): Description of attr2
"""
备注
Python 2/3 compatible annotations aren’t currently supported by Sphinx and won’t show up in the docs.
配置¶
以下列出了napoleon使用的所有设置及其默认值.这些设置可以在Sphinx的 conf.py 文件中更改.确保在 conf.py 中启用”sphinx.ext.napoleon”:
# conf.py
# Add any Sphinx extension module names here, as strings
extensions = ['sphinx.ext.napoleon']
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_preprocess_types = False
napoleon_type_aliases = None
napoleon_attr_annotations = True
- napoleon_google_docstring¶
解析 Google style 文档字符串时为真.为假则禁用对 Google 风格文档字符串的支持.*默认为 True.*
- napoleon_include_init_with_doc¶
将
__init___的文档字符串与类的文档字符串分开列出.设置为 False 则使用 Sphinx 的默认行为,即将__init___的文档字符串视为类文档的一部分.*默认为 False.*如果为真:
def __init__(self): """ This will be included in the docs because it has a docstring """ def __init__(self): # This will NOT be included in the docs
- napoleon_include_private_with_doc¶
在文档中包含带文档字符串的私有成员(如
_membername).若为 False,则恢复到 Sphinx 的默认行为.*默认为 False.*如果为真:
def _included(self): """ This will be included in the docs because it has a docstring """ pass def _skipped(self): # This will NOT be included in the docs pass
- napoleon_include_special_with_doc¶
在文档中包含特殊成员(如
__membername__)的文档字符串时为 True.为 False 时,采用 Sphinx 的默认行为.*默认为 True.*如果为真:
def __str__(self): """ This will be included in the docs because it has a docstring """ return unicode(self).encode('utf-8') def __unicode__(self): # This will NOT be included in the docs return unicode(self.__class__.__name__)
- napoleon_use_admonition_for_examples¶
将
.. admonition ::指令用于 示例 和 示例 部分时为 True.使用.. rubric::指令则为 False.根据所使用的 HTML 主题,可能有的看起来比其他的更好.*默认为 False.*这个 NumPy 风格 代码片段将被转换为如下格式:
Example ------- This is just a quick example
如果为真:
.. admonition:: Example This is just a quick example
如果是假:
.. rubric:: Example This is just a quick example
- napoleon_use_admonition_for_notes¶
使用
.. admonition ::指令用于 Notes 部分为真.相反使用.. rubric::指令为假.*默认值为假.*备注
单独的 Note 部分将始终转换为
.. note::指令.
- napoleon_use_admonition_for_references¶
将
.. admonition ::指令用于 参考 部分设为 True.将.. rubric::指令用于此部分设为 False.*默认为 False.*
- napoleon_use_ivar¶
在 `` :ivar:`` 角色中用于实例变量.如果为False,则使用
.. attribute::指令.*默认为False.*这个 NumPy 风格 代码片段将被转换为如下格式:
Attributes ---------- attr1 : int Description of `attr1`如果为真:
:ivar attr1: Description of `attr1` :vartype attr1: int
如果是假:
.. attribute:: attr1 Description of `attr1` :type: int
- napoleon_use_param¶
对于每个函数参数,使用
:param:角色为真.对所有参数使用单一的:parameters:角色为假. 默认为真.这个 NumPy 风格 代码片段将被转换为如下格式:
Parameters ---------- arg1 : str Description of `arg1` arg2 : int, optional Description of `arg2`, defaults to 0如果为真:
:param arg1: Description of `arg1` :type arg1: str :param arg2: Description of `arg2`, defaults to 0 :type arg2: :class:`int`, *optional*
如果是假:
:parameters: * **arg1** (*str*) -- Description of `arg1` * **arg2** (*int, optional*) -- Description of `arg2`, defaults to 0
- napoleon_use_keyword¶
使用
:keyword:角色为每个函数关键字参数.如果为 False,则为所有关键字使用单个:keyword arguments:角色.*默认为 True.*这与
napoleon_use_param的行为类似.请注意,与 docutils 不同,:keyword:和:param:不会以相同方式处理 - 将会有一个单独的 “关键字参数” 部分,按照 “参数” 部分的方式呈现(如果可能会创建类型链接)
- napoleon_use_rtype¶
将
:rtype:角色用于返回类型时为 True.为 False 时,返回类型将与描述一起输出.*默认为 True.*这个 NumPy 风格 代码片段将被转换为如下格式:
Returns ------- bool True if successful, False otherwise如果为真:
:returns: True if successful, False otherwise :rtype: bool
如果是假:
:returns: *bool* -- True if successful, False otherwise
- napoleon_preprocess_types¶
将文档字符串中的类型定义转换为引用.默认值为 False.
Added in version 3.2.1.
在 3.5 版本发生变更: 也请对Google风格的文档字符串进行预处理.
- napoleon_type_aliases¶
将类型名称映射到其他名称或引用的映射.仅在
napoleon_use_param = True时有效. 默认为 None.与:
napoleon_type_aliases = { "CustomType": "mypackage.CustomType", "dict-like": ":term:`dict-like <mapping>`", }这个 NumPy 风格 的代码片段:
Parameters ---------- arg1 : CustomType Description of `arg1` arg2 : dict-like Description of `arg2`变为:
:param arg1: Description of `arg1` :type arg1: mypackage.CustomType :param arg2: Description of `arg2` :type arg2: :term:`dict-like <mapping>`
Added in version 3.2.
- napoleon_attr_annotations¶
允许在类中使用 PEP 526 属性注解. 如果一个属性在文档字符串中没有类型而在类体中有注解,则使用该注解的类型.
Added in version 3.4.
- napoleon_custom_sections¶
添加要包含的自定义部分列表,以扩展解析部分的列表. 默认为 None.
条目可以是字符串或元组,具体取决于意图:
要创建一个自定义的”通用”部分,只需传递一个字符串.
要为已有的部分创建别名,传递一个包含别名名称和原始部分的元组,顺序要正确.
要创建一个自定义部分,使其显示方式类似于参数或返回部分,传递一个元组,包含自定义部分名称和字符串值 “params_style” 或 “returns_style”.
如果条目只是一个字符串,它将被解释为通用部分的标题.如果条目是一个元组/列表/索引容器,则第一个条目是部分的名称,第二个是要模拟的部分键.如果第二个条目的值是”params_style”或”returns_style”,自定义部分将像参数部分或返回部分那样显示.
Added in version 1.8.
在 3.5 版本发生变更: 支持
params_style和returns_style