sphinx.ext.napoleon – NumPy 和 Google 风格文档字符串支持

模块作者:Rob Ruana

在 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 很棒,但它创建了视觉上密集、难以阅读的 文档字符串。将上面的混乱与根据 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 是一个 扩展,使 Sphinx 能够解析 NumPyGoogle 风格的文档字符串 - Khan Academy 推荐的风格。

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

入门指南

  1. 设置 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
    

文档字符串

Napoleon 解释 autodoc 可以找到的每个文档字符串,包括 modulesclassesattributesmethodsfunctionsvariables 上的文档字符串。在每个文档字符串内部,特殊格式化的 章节 被解析并转换为 reStructuredText。

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

文档字符串章节

支持以下所有章节标题

  • Args (Parameters 的别名)

  • Arguments (Parameters 的别名)

  • 注意

  • 属性

  • 警告

  • 危险

  • 错误

  • 示例

  • 示例

  • 提示

  • 重要

  • Keyword Args (Keyword Arguments 的别名)

  • Keyword Arguments

  • 方法

  • 注意

  • 注释

  • Other Parameters

  • 参数

  • Return (Returns 的别名)

  • 返回

  • Raise (Raises 的别名)

  • 引发

  • 参考

  • See Also

  • 技巧

  • 待办事项

  • 警告

  • Warnings (Warning 的别名)

  • Warn (Warns 的别名)

  • 警告

  • Yield (Yields 的别名)

  • 产生

Google vs NumPy

Napoleon 支持两种风格的文档字符串:GoogleNumPy。两种风格之间的主要区别在于,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 风格往往更容易阅读。

风格的选择在很大程度上是美观的,但两种风格不应混合使用。为你的项目选择一种风格并保持一致。

类型注解

PEP 484 引入了一种在 Python 代码中表达类型的标准方法。这是直接在文档字符串中表达类型的替代方法。根据 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

文档字符串中带有类型的 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

True 以解析 Google 风格 的文档字符串。False 以禁用对 Google 风格文档字符串的支持。

napoleon_numpy_docstring
类型:
bool
默认值:
True

True 以解析 NumPy 风格 的文档字符串。False 以禁用对 NumPy 风格文档字符串的支持。

napoleon_include_init_with_doc
类型:
bool
默认值:
False

True 以将 __init___ 文档字符串与类文档字符串分开列出。False 以回退到 Sphinx 的默认行为,该行为将 __init___ 文档字符串视为类文档的一部分。

如果为 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
类型:
bool
默认值:
False

True 以在文档中包含带有文档字符串的私有成员(如 _membername)。False 以回退到 Sphinx 的默认行为。

如果为 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
类型:
bool
默认值:
True

True 以在文档中包含带有文档字符串的特殊成员(如 __membername__)。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
类型:
bool
默认值:
False

True 以对 ExampleExamples 章节使用 .. admonition:: 指令。False 以改为使用 .. rubric:: 指令。根据使用的 HTML 主题,一种可能比另一种更好看。

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

True 以对 Notes 章节使用 .. admonition:: 指令。False 以改为使用 .. rubric:: 指令。

注意

单数 Note 章节将始终转换为 .. note:: 指令。

napoleon_use_admonition_for_references
类型:
bool
默认值:
False

True 以对 References 章节使用 .. admonition:: 指令。False 以改为使用 .. rubric:: 指令。

napoleon_use_ivar
类型:
bool
默认值:
False

True 以对实例变量使用 :ivar: 角色。False 以改为使用 .. attribute:: 指令。

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

True 以对每个函数参数使用 :param: 角色。False 以对所有参数使用单个 :parameters: 角色。

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

True 以对每个函数关键字参数使用 :keyword: 角色。False 以对所有关键字使用单个 :keyword arguments: 角色。

这与 napoleon_use_param 的行为类似。请注意,与 docutils 不同,:keyword::param: 将不会被同等对待 - 将有一个单独的 “Keyword Arguments” 章节,以与 “Parameters” 章节相同的方式呈现(如果可能,创建类型链接)

另请参阅

napoleon_use_param

napoleon_use_rtype
类型:
bool
默认值:
True

True 以对返回类型使用 :rtype: 角色。False 以内联描述输出返回类型。

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

True 以将文档字符串中的类型定义转换为引用。

在 3.2.1 版本中添加。

在 3.5 版本中更改:也预处理 Google 风格的文档字符串。

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 风格 代码片段

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

True 以允许在类中使用 PEP 526 属性注解。如果属性在文档字符串中没有类型文档,并且在类主体中具有注解,则使用该类型。

在 3.4 版本中添加。

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

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

条目可以是字符串或元组,具体取决于意图

  • 要创建自定义 “通用” 章节,只需传递一个字符串。

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

  • 要创建自定义章节,使其显示方式类似于参数或返回章节,请传递一个元组,其中包含自定义章节名称和一个字符串值 “params_style” 或 “returns_style”。

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

在 1.8 版本中添加。

在 3.5 版本中更改:支持 params_stylereturns_style