sphinx.ext.napoleon -- 支持 NumPy 和 Google 风格的文档字符串¶
Module author: 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 很棒,但它生成的文档字符串(docstrings)在视觉上显得密集,难以阅读。 文档字符串. 将上面的混乱与根据 Google Python 风格指南 重写的相同内容进行比较:
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
更多的可读性,不是吗?
Napoleon extension 使 Sphinx 能够解析 NumPy 和 Google 风格的文档字符串——由 Khan Academy 推荐的风格。
Napoleon 是一个预处理器,它解析 NumPy 和 Google 风格的文档字符串,并在 Sphinx 尝试解析它们之前将它们转换为 reStructuredText。这是在 Sphinx 处理文档的过程中发生的中间步骤,因此它不会修改您实际的源代码文件中的任何文档字符串。
快速入门¶
在 设置 Sphinx 以构建你的文档后,在 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
文档字符串¶
Napoleon 解析 autodoc 可以找到的每个文档字符串,包括: modules, classes, attributes, methods, functions 和 variables 的文档字符串。在每个文档字符串中,特殊格式的 Sections 被解析并转换为 reStructuredText。
所有标准的 reStructuredText 格式仍然可以正常工作。
文档字符串部分¶
以下部分 headers 被支持:
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 vs NumPy¶
Napoleon 支持两种风格的文档字符串:Google 和 NumPy。这两种风格的主要区别在于,Google 使用缩进来分隔部分,而 NumPy 使用下划线。
Google style:
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 style:
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 style 需要更多的垂直空间,而 Google style 倾向于使用更多的水平空间。Google style 更容易阅读短和简单的文档字符串,而 NumPy style 更容易阅读长和深入的文档字符串。
选择风格主要是审美,但是两种风格不应该混合。为您的项目选择一种风格,并保持一致。
Type Annotations¶
PEP 484 引入了一种在 Python 代码中表达类型的标准方法。这种方法是通过在文档字符串中直接表达类型来实现的。
带有 Python 3 类型注解的 Google 风格:
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
"""
Note
Python 2/3 兼容的注解 目前不受 Sphinx 支持,并且不会显示在文档中。
配置¶
在 Sphinx conf.py 文件中列出了所有由 napoleon 使用的设置及其默认值。这些设置可以在 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¶
True 解析 Google style 文档字符串。False 禁用对 Google style 文档字符串的支持。默认为 True。
- napoleon_numpy_docstring¶
True 解析 NumPy style 文档字符串。False 禁用对 NumPy style 文档字符串的支持。默认为 True。
- napoleon_include_init_with_doc¶
True 将
__init___文档字符串与类文档字符串分开列出。False 回退到 Sphinx 的默认行为,将__init___文档字符串视为类文档的一部分。默认为 False。如果为 True:
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¶
True 包含私有成员(例如
_membername)的文档字符串。False 回退到 Sphinx 的默认行为。默认为 False。如果为 True:
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¶
True 包含特殊成员(例如
__membername__)的文档字符串。False 回退到 Sphinx 的默认行为。默认为 True。如果为 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¶
True 使用
.. admonition::指令来显示 Example 和 Examples 部分。False 使用.. rubric::指令代替。可能会根据使用的 HTML 主题而有所不同。默认为 False。这个 NumPy 风格 的代码片段将会被转换如下:
Example ------- This is just a quick example
如果为 True:
.. admonition:: Example This is just a quick example
如果为 False:
.. rubric:: Example This is just a quick example
- napoleon_use_admonition_for_notes¶
使用
.. admonition::指令来显示 Notes 部分。False 使用.. rubric::指令代替。默认为 False。"Note
单个 Note 部分将始终被转换为
.. note::指令。See also
- napoleon_use_admonition_for_references¶
使用
.. admonition::指令来显示 References 部分。False 使用.. rubric::指令代替。默认为 False。See also
- napoleon_use_ivar¶
使用
:ivar:角色来显示实例变量。False 使用.. attribute::指令代替。默认为 False。这个 NumPy 风格 的代码片段将会被转换如下:
Attributes ---------- attr1 : int Description of `attr1`如果为 True:
:ivar attr1: Description of `attr1` :vartype attr1: int
如果为 False:
.. attribute:: attr1 Description of `attr1` :type: int
- napoleon_use_param¶
使用
:param:角色来显示每个函数参数。False 使用:parameters:角色来显示所有的参数。默认为 True。这个 NumPy 风格 的代码片段将会被转换如下:
Parameters ---------- arg1 : str Description of `arg1` arg2 : int, optional Description of `arg2`, defaults to 0如果为 True:
:param arg1: Description of `arg1` :type arg1: str :param arg2: Description of `arg2`, defaults to 0 :type arg2: :class:`int`, *optional*
如果为 False:
: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:将不会被视为相同的方式 - 会有单独的 "Keyword Arguments" 部分,与 "Parameters" 部分相同(如果可能,会创建类型链接)See also
- napoleon_use_rtype¶
使用
:rtype:角色来显示返回类型。False 内联显示返回类型。默认为 True。这个 NumPy 风格 的代码片段将会被转换如下:
Returns ------- bool True if successful, False otherwise如果为 True:
:returns: True if successful, False otherwise :rtype: bool
如果为 False:
:returns: *bool* -- True if successful, False otherwise
- napoleon_preprocess_types¶
使用
:rtype:角色来显示返回类型。默认为 False。Added in version 3.2.1.
Changed in version 3.5: 也处理 Google 风格的文档字符串。
- napoleon_type_aliases¶
将类型名称映射到其他名称或引用。仅当
napoleon_use_param = True时有效。默认为 None。With:
napoleon_type_aliases = { "CustomType": "mypackage.CustomType", "dict-like": ":term:`dict-like <mapping>`", }NumPy style 的代码片段:
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。
这些条目可以是字符串,也可以是元组,取决于意图:
要创建自定义的 "generic" 部分,只需传递字符串。
要为现有的分区创建别名,请按顺序传递包含别名名称和原始名称的元组。
要创建自定义分区,该分区显示与参数或返回部分类似的部分,请按顺序传递包含自定义分区名称和字符串值 "params_style" 或 "returns_style" 的元组。
如果条目只是字符串,它被解释为通用分区的标题。如果条目是元组/列表/索引容器,第一个条目是分区的名称,第二个条目是要模仿的分区键。如果第二个条目值是 "params_style" 或 "returns_style",自定义分区将显示与参数分区或返回分区类似的部分。
Added in version 1.8.
Changed in version 3.5: 支持
params_style和returns_style