:模式:sphinx.ext.napoleon——支持NumPy和Google风格的文档字符串

模块作者: 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 is great, but it creates visually dense, hard to read docstrings. Compare the jumble above to the same thing rewritten according to the 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是一个:term:‘extension’,它使Sphinx能够解析“NumPy”和“Google”风格的docstrings,这是“Khan Academy”推荐的样式。

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

快速上手

  1. After setting up Sphinx to build your docs, enable napoleon in the Sphinx conf.py file:

    # conf.py
    
    # Add napoleon to the extensions list
    extensions = ['sphinx.ext.napoleon']
    
  2. Use sphinx-apidoc to build your API documentation:

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

文档字符串

拿破仑解释每个文档字符串: mod:autodoc<sphinx.ext.autodoc>`可以找到,包括文档字符串: `modules`classes``attributesmethods`functions``和`variables`。在每个文档字符串中,经过特殊格式化的“Sections”被解析并转换为restructedText。

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

文档字符串部分

支持以下所有节标题:

  • Args (alias of Parameters)

  • Arguments (参数别名)

  • 注意

  • 属性

  • 小心

  • 危险

  • 错误

  • 示例

  • 示例

  • 提示

  • 重要

  • Keyword Args (参数别名)

  • 关键字参数

  • 方法

  • 笔记

  • 笔记

  • 其他参数

  • 参数

  • 返回 (返回别名)

  • 返回

  • Raise (Raise别名)

  • 提升

  • 参考

  • 请参阅

  • 贴士

  • 待办

  • 警告

  • 警告 (警告别名)

  • Warn (Warns别名)

  • 警告

  • ``产量``*(产量别名)*

  • 产量

Google 和 NumPy

Napoleon支持两种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

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 introduced a standard way to express types in Python code. This is an alternative to expressing types directly in docstrings. One benefit of expressing types according to PEP 484 is that type checkers and IDEs can take advantage of them for static code analysis. PEP 484 was then extended by PEP 526 which introduced a similar way to annotate variables (and attributes).

带有python3类型注释的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中类型的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
    """

备注

`Sphinx目前不支持Python2/3兼容的注释,因此不会出现在文档中。

配置

Listed below are all the settings used by napoleon and their default values. These settings can be changed in the Sphinx conf.py file. Make sure that “sphinx.ext.napoleon” is enabled in 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”docstrings,则为True。False禁用对Google样式docstring的支持。默认为True

napoleon_numpy_docstring

若要分析“NumPy-style”docstrings,则为True。False禁用对NumPy样式docstring的支持。默认为True

napoleon_include_init_with_doc

如果为True,则从类docstring中分别列出“``uUu init_Uu2;`docstring”。False返回到Sphinx的默认行为,该行为将“``uUu init_Uu2;”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

如果为True,则在文档中使用docstrings包含私有成员(如“u membername``”)。False返回到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

如果为True,则在文档中包含带有DocString的特殊成员(如“uUu 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

如果要使用’’. admonition:::``用于**示例**和**示例**部分的指令。使用`..改为:``指令。一个可能比另一个更好,这取决于使用了什么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::``针对**注释**部分的指令。使用`..改为:``指令。默认为False

备注

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

napoleon_use_admonition_for_references

如果要使用’’..警告:``针对**引用**部分的指令。使用`..改为:``指令。默认为False

napoleon_use_ivar

如果为True,则将“%ivar:”角色用于实例变量。使用。。改为属性::``指令。默认为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

如果为True,则为每个函数参数使用一个“:param:”角色。如果要对所有参数使用单个“参数:`”角色,则返回False。默认为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

如果为True,则为每个函数关键字参数使用一个“:keyword:”角色。如果要对所有关键字使用单个“`:keyword参数:``角色”,则返回False。默认为True

This behaves similarly to napoleon_use_param. Note unlike docutils, :keyword: and :param: will not be treated the same way - there will be a separate “Keyword Arguments” section, rendered in the same fashion as “Parameters” section (type links created if possible)

napoleon_use_rtype

如果为True,则对返回类型使用“: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 to convert the type definitions in the docstrings as references. Defaults to False.

Added in version 3.2.1.

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

napoleon_type_aliases

将类型名转换为其他名称或引用的映射。只有在“napoleonu 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>`

Added in version 3.2.

napoleon_attr_annotations

True to allow using PEP 526 attributes annotations in classes. If an attribute is documented in the docstring without a type and has an annotation in the class body, that type is used.

Added in version 3.4.

napoleon_custom_sections

添加一个要包括的自定义章节列表,扩大解析的章节列表。默认为None

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

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

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

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

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

Added in version 1.8.

在 3.5 版本发生变更: 支持 params_style``和``returns_style