sphinx.ext.napoleon – 支持NumPy和Google风格的文档字符串¶
模块作者:Rob Ruana
1.3 新版功能.
概观¶
你是否厌倦了编写看起来像这样的 docstrings 字符串:
: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
更清晰,没有?
Napoleon是一个 extension ,它使Sphinx能够解析 NumPy 和 Google 风格的文档字符串 - 这是 Khan Academy 推荐的风格。
Napoleon是一个预处理器,它解析 NumPy 和 Google 样式的文档字符串,并在Sphinx尝试解析之前将它们转换为reStructuredText。当Sphinx处理文档时,这会在中间步骤中发生,因此它不会修改实际源代码文件中的任何文档字符串。
入门¶
之后 设置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
Docstrings¶
拿破仑解释每一个文档字符串 autodoc 可以找到,包括docstrings: modules , classes , attributes , methods , functions 和 variables 。 在每个docstring中,特殊格式化的 Sections 被解析并转换为 reStructuredText 。
所有标准的reStructuredText格式仍然按预期工作。
Docstring部分¶
支持以下所有节标题:
Args(参数的别名)Arguments(参数的别名)AttentionAttributesCautionDangerErrorExampleExamplesHintImportantKeyword Args(关键字参数的别名)Keyword ArgumentsMethodsNoteNotesOther ParametersParametersReturn(退货的别名)ReturnsRaisesReferencesSee AlsoTipTodoWarningWarnings(警告的别名)WarnsYield(收益率的别名)Yields
Google与NumPy¶
拿破仑支持两种类型的文档字符串: 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风格更容易阅读。
Khan Academy 建议使用Google风格。
风格之间的选择很大程度上是审美的,但两种风格不应混为一谈。为您的项目选择一种样式并与之保持一致。
输入注释¶
PEP 484 引入了一种在Python代码中表达类型的标准方法。 这是直接在docstrings中表达类型的替代方法。 根据 PEP 484 表达类型的一个好处是类型检查器和IDE可以利用它们进行静态代码分析。
采用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
带有文档字符串类型的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
注解
Sphinx目前不支持 Python 2/3 compatible annotations ,并且不会在文档中显示。
配置¶
下面列出的是拿破仑使用的所有设置及其默认值。 可以在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_google_docstring¶ 是的,可以解析 Google style docstrings。如果禁用对Google样式文档字符串的支持,则为false。 默认为True。
-
napoleon_numpy_docstring¶ 是真的解析 NumPy style docstrings。如果禁用对NumPy样式文档字符串的支持,则为false。 默认为True。
-
napoleon_include_init_with_doc¶ 如果将
__init___docstrings与类 docstring 分开列出,则为True。 回到Sphinx的默认行为是错误的,它将__init___docstring 视为类文档的一部分。 默认为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¶ 如果包含文档中的docstrings私有成员(如
_membername),则为True。 错误地回归到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¶ 如果在文档中包含docstrings的特殊成员(例如
__membername__),则为True。 错误地回归到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¶ 对于 Example 和 Example 部分,使用
.. admonition::指令。 错误地使用.. rubric::指令。根据使用的HTML主题,一个可能看起来比另一个好。 默认为False。这个 NumPy style 片段将按如下方式转换:
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¶ 对于 Notes 部分,使用
.. admonition::指令。错误地使用.. rubric::指令。 默认为False。注解
单数 Note 部分将始终转换为
.. note::指令。参见
napoleon_use_admonition_for_examples
-
napoleon_use_admonition_for_references¶ 对于 References 部分,使用
.. admonition::指令。错误地使用.. rubric::指令。 默认为False。参见
napoleon_use_admonition_for_examples
-
napoleon_use_ivar¶ 如果为实例变量,则使用
:ivar:角色。错误地使用.. attribute::指令。 默认为False。这个 NumPy style 片段将按如下方式转换:
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:角色,则为 True。对所有参数使用单个:parameters:角色为假。 默认为 True。这个 NumPy style 片段将按如下方式转换:
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: int, optional
如果 False:
:parameters: * **arg1** (*str*) -- Description of `arg1` * **arg2** (*int, optional*) -- Description of `arg2`, defaults to 0
-
napoleon_use_keyword¶ 如果为每个函数关键字参数使用
:keyword:角色,则为 True。对所有关键字使用单个:keyword arguments:角色是错误的。 默认为 True。其行为类似于
napoleon_use_param。请注意,与docutils不同,:keyword:和:param:将不会以同样的方式处理 - 将有一个单独的 “关键字参数” 部分,以与“参数 “相同的方式呈现” 部分(如果可能,创建类型链接)参见
napoleon_use_param
-
napoleon_use_rtype¶ 如果为返回类型,则使用
:rtype:角色。如果输出与描述内联的返回类型,则返回false。 默认为 True。这个 NumPy style 片段将按如下方式转换:
Returns ------- bool True if successful, False otherwise如果 True:
:returns: True if successful, False otherwise :rtype: bool
如果 False:
:returns: *bool* -- True if successful, False otherwise