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能够解析 NumPyGoogle 风格的docstrings,这是 Khan Academy 推荐的样式。

Napoleon是一个预处理器,它可以解析 NumPyGoogle 风格的docstring,并在Sphinx尝试解析它们之前将它们转换为reStructuredText。这发生在Sphinx处理文档的中间步骤中,因此它不会修改实际源代码文件中的任何文档字符串。

快速上手

  1. setting up Sphinx 后构建你的文档,在Sphinx的 conf.py 文件中启用napoleon:

    # conf.py
    
    # Add napoleon to the extensions list
    extensions = ['sphinx.ext.napoleon']
    
  2. 使用 sphinx-apidoc 来构建你的API文档:

    $ sphinx-apidoc -f -o docs/source projectdir
    

Docstrings

Napoleon解释每个 autodoc 找到的Docstrings,包括 modulesclassesattributesmethodsfunctionsvariables 的Docstrings。在每个Docstrings中,经过特殊格式化的 Sections 被解析并转换为restructedText。

所有标准的restructedText格式仍按预期工作。

Docstrings章节

支持以下所有章节标题:

  • Args (alias of Parameters)

  • Arguments (参数别名)

  • Attention

  • Attributes

  • Caution

  • Danger

  • Error

  • Example

  • Examples

  • Hint

  • Important

  • Keyword Args (参数别名)

  • Keyword Arguments

  • Methods

  • Note

  • Notes

  • Other Parameters

  • Parameters

  • Return (返回别名)

  • Returns

  • Raise (Raises的别名)

  • Raises

  • References

  • See Also

  • Tip

  • Todo

  • Warning

  • Warnings (Warning的别名)

  • Warn (Warns的别名)

  • Warns

  • Yield (Yields的别名)

  • Yields

Google 对比 NumPy

Napoleon支持两种docstring样式: GoogleNumPy 。这两种风格的主要区别在于Google使用缩进来分隔sections,而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

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风格倾向于使用更多的水平空间。对于简短的docstring,Google样式更容易阅读,而NumPy样式对于长而深入的docstring更容易阅读。

风格之间的选择很大程度上是审美决定的,但这两种风格不应该混为一谈。为你的项目选择一种风格,并与之保持一致。

类型批注

PEP 484 引入了一种在Python代码中表达类型的标准方法。这是直接在docstrings中表达类型的替代方法。根据 PEP 484 表达类型的一个好处是类型检查器和IDE可以利用它们进行静态代码分析。PEP 484 随后被 PEP 526 扩展,后者引入了一种类似的方法来注释变量(和属性)。

带类型注释的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

docstrings带types的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
    """

配置

下边列出了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
类型:
bool
默认:
True

为真则解析 Google style docstrings。为假则禁用对Google风格docstrings的支持。

napoleon_numpy_docstring
类型:
bool
默认:
True

为真则解析 NumPy style docstrings。为假则禁用对NumPy风格docstrings的支持。

napoleon_include_init_with_doc
类型:
bool
默认:
False

为真则从类的docstrings里单独列出 __init___ 的docstrings。为假则回退到Sphinx的默认行为,将 __init___ 的docstrings视为类的docstrings的一部分。

如果为真

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
类型:
bool
默认:
False

为真则在文档中包含带有docstrings的私有成员(如 _membername)。为假则回退到Sphinx的默认行为。

如果为真

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
类型:
bool
默认:
True

为真则在文档中包含带有docstrings的特殊成员(如 __membername__)。为假则回退到Sphinx的默认行为。

如果为真

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
类型:
bool
默认:
False

为真则对 ExampleExamples 部分使用 .. admonition:: 指令。为假则改用 .. rubric:: 指令。根据使用的HTML主题,可能会有不同的外观效果。

这个 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
类型:
bool
默认:
False

为真则对 Notes 部分使用 .. admonition:: 指令。为假则改用 .. rubric:: 指令。

备注

单数的 注释 部分将始终转换为 .. note:: 指令。

napoleon_use_admonition_for_references
类型:
bool
默认:
False

为真则对 References 部分使用 .. admonition:: 指令。为假则改用 .. rubric:: 指令。

napoleon_use_ivar
类型:
bool
默认:
False

为真则对实例变量使用 :ivar: 角色。为假则改用 .. attribute:: 指令。

这个 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
类型:
bool
默认:
True

为真则对每个函数参数使用 :param: 角色。为假则对所有参数使用单个 :parameters: 角色。

这个 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
类型:
bool
默认:
True

为真则对每个函数关键字参数使用 :keyword: 角色。为假则对所有关键字使用单个 :keyword arguments: 角色。

napoleon_use_param 的行为类似。注意,与docutils不同,:keyword::param: 不会以相同的方式处理 - 将有一个单独的 "Keyword Arguments" 部分,以与 "Parameters" 部分相同的方式呈现(如果可能的话会创建类型链接)

napoleon_use_rtype
类型:
bool
默认:
True

为真则对返回类型使用 :rtype: 角色。为假则将返回类型与描述内联输出。

这个 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
类型:
bool
默认:
False

真则将docstrings中的类型定义转换为引用。

在 3.2.1 版本加入.

在 3.5 版本发生变更: 对Google风格的docstrings也进行预处理。

napoleon_type_aliases
类型:
dict[str, str] | None
默认:
None

一个映射,用于将类型名称转换为其他名称或引用。仅当 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>`

在 3.2 版本加入.

napoleon_attr_annotations
类型:
bool
默认:
True

为真则允许在类中使用 PEP 526 属性注释。如果在docstrings中没有类型而在类主体中有注释的属性,则使用该类型。

在 3.4 版本加入.

napoleon_custom_sections
类型:
Sequence[str | tuple[str, str]] | None
默认:
None

添加要包含的自定义章节列表,扩展已解析章节的列表。

这些条目既可以是字符串,也可以是元组,这取决于意图:

  • 要创建一个自定义的"generic"章节,只需传递一个字符串。

  • 要为一个现有的章节创建一个别名,请传递一个包含别名和原始名称的元组,按顺序排列。

  • 要创建一个像参数或返回部分那样显示的自定义章节,请传递一个元组包含自定义章节名称和一个字符串值,"params_style" 或 "returns_style"。

如果一个条目只是一个字符串,它将被解释为一个通用节的头。如果条目是一个元组/列表/索引容器,第一个条目是章节的名称,第二个是要模仿的章节键。如果第二个条目的值是 "params_style" 或 "returns_style",自定义节将像参数部分或返回部分那样显示。

在 1.8 版本加入.

在 3.5 版本发生变更: 支持 params_stylereturns_style