sphinx.ext.napoleon
--支持numpy和google风格的docstrings¶
模块作者: 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 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
更清晰,不是吗?
拿破仑是 extension 这使得Sphinx能够分析 NumPy 和 Google Style DocStrings-建议的样式 Khan Academy .
拿破仑是分析 NumPy 和 Google 设置docStrings的样式,并在sphinx尝试解析它们之前将其转换为restructuredtext。这发生在Sphinx处理文档时的中间步骤中,因此它不会修改实际源代码文件中的任何docstring。
入门¶
之后 setting up Sphinx 要构建您的文档,请在Sphinx中启用拿破仑
conf.py
文件::# conf.py # Add napoleon to the extensions list extensions = ['sphinx.ext.napoleon']
使用
sphinx-apidoc
要构建API文档,请执行以下操作:$ sphinx-apidoc -f -o docs/source projectdir
文档字符串¶
拿破仑解释了每一个 autodoc
可以找到,包括文档字符串: modules
, classes
, attributes
, methods
, functions
和 variables
. 在每个docstring中,特别格式化 Sections 被解析并转换为RestructuredText。
所有标准的 reStructuredText 格式仍按预期工作。
文档字符串部分¶
支持以下所有节头:
Args
(参数别名)Arguments
(参数别名)Attention
Attributes
Caution
Danger
Error
Example
Examples
Hint
Important
Keyword Args
(关键字参数的别名)Keyword Arguments
Methods
Note
Notes
Other Parameters
Parameters
Return
(返回别名)Returns
Raise
(alias of Raises)Raises
References
See Also
Tip
Todo
Warning
Warnings
(警告别名)Warn
(alias of Warns)Warns
Yield
(产量别名)Yields
谷歌vs麻木¶
拿破仑支持两种类型的docstring: Google 和 NumPy . 这两种样式的主要区别在于Google使用缩进来分隔各个部分,而Numpy使用下划线。
谷歌风格:
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
麻木风格:
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样式更容易阅读。
风格之间的选择在很大程度上是审美的,但这两种风格不应该混为一谈。为你的项目选择一种风格并与之保持一致。
类型批注¶
PEP 484 介绍了一种在Python代码中表示类型的标准方法。这是直接在文档字符串中表示类型的替代方法。表示类型的一个好处是根据 PEP 484 类型检查器和IDE可以利用它们进行静态代码分析。 PEP 484 然后扩展为 PEP 526 它引入了一种类似的方法来注释变量(和属性)。
带有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
"""
备注
Python 2/3 compatible annotations 目前没有Sphinx的支持,也不会出现在文档中。
配置¶
下面列出了拿破仑使用的所有设置及其缺省值。可以在Sphinx中更改这些设置 conf.py
文件。确保在中启用了“sphinx.ext.napolon conf.py
**
# 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 文档字符串。如果为false,则禁用对Google样式DocStrings的支持。 默认为true。
- napoleon_numpy_docstring¶
真实解析 NumPy style 文档字符串。如果为false,则禁用对numpy样式docstrings的支持。 默认为true。
- napoleon_include_init_with_doc¶
名列前茅
__init___
docstring与类docstring分开。假以回到Sphinx的默认行为,这考虑到__init___
作为类文档的一部分的docstring。 默认为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
)文档中包含文档字符串。假以恢复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__
)文档中包含文档字符串。假以恢复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::
指令 例子 和 实例 部分。如果使用.. rubric::
改为指令。根据所使用的HTML主题,其中一个看起来可能比另一个更好。 默认为false。这个 NumPy style 代码段将按以下方式转换:
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::
指令 笔记 部分。如果使用.. rubric::
改为指令。 默认为false。备注
单数 Note 节将始终转换为
.. note::
指令。
- napoleon_use_admonition_for_references¶
真实使用
.. admonition::
指令 工具书类 部分。如果使用.. rubric::
改为指令。 默认为false。
- napoleon_use_ivar¶
真实使用
:ivar:
实例变量的角色。如果使用.. attribute::
改为指令。 默认为false。这个 NumPy style 代码段将按以下方式转换:
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:
所有参数的角色。 默认为true。这个 NumPy style 代码段将按以下方式转换:
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:
每个函数关键字参数的角色。如果使用单个:keyword arguments:
所有关键字的角色。 默认为true。它的行为类似于
napoleon_use_param
。注意与docutils不同,:keyword:
和:param:
将不会以相同的方式处理--将有一个单独的“关键字参数”部分,以与“参数”部分相同的方式呈现(如果可能,请输入链接)
- napoleon_use_rtype¶
真实使用
:rtype:
返回类型的角色。如果返回类型与描述内联,则返回false。 默认为true。这个 NumPy style 代码段将按以下方式转换:
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¶
如果为True,则将文档字符串中的类型定义转换为引用。默认为 False 。
Added in version 3.2.1.
在 3.5 版本发生变更: 也要对Google样式的文档字符串进行预处理。
- napoleon_type_aliases¶
将类型名转换为其他名称或引用的映射。只有在
napoleon_use_param = True
. 默认为无。有:
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¶
如果为True,则允许使用 PEP 526 类中的属性批注。如果某个属性记录在文档字符串中,但没有类型,并且在类体中有注释,则使用该类型。
Added in version 3.4.
- napoleon_custom_sections¶
添加要包括的自定义节列表,从而展开已解析节的列表。 默认为无。
条目可以是字符串,也可以是元组,具体取决于用途:
要创建自定义“通用”节,只需传递一个字符串。
要为现有节创建别名,请按该顺序传递包含别名和原始名称的元组。
要创建与PARAMETERS或RETURNS节类似的自定义节,请传递一个包含自定义节名称和字符串值“params_style”或“Returns_style”的元组。
如果条目只是一个字符串,它将被解释为泛型部分的标题。如果条目是元组/列表/索引容器,则第一个条目是节的名称,第二个是要模拟的节键。如果第二个输入值为“params_style”或“Returns_style”,则自定义节将与Parameters节或Returns节一样显示。
Added in version 1.8.
在 3.5 版本发生变更: 支持
params_style
和returns_style