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 很棒,但它视觉上很密集,难以阅读 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能够解析这两个 NumPyGoogle 样式文档字符串-推荐的样式 Khan Academy

拿破仑是一个预处理器,它解析 NumPyGoogle 设置文档字符串的样式,并在Sphinx尝试解析它们之前将它们转换为reStrutiredText。这发生在Sphinx处理文档的中间步骤中,因此它不会修改实际源代码文件中的任何文档字符串。

开始

  1. setting up Sphinx 要构建您的文档,请在Sphinx中启用拿破仑 conf.py 文件:

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

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

文档字符串

拿破仑解释了每一个文档字符串 autodoc 可以找到,包括以下位置的文档字符串: modulesclassesattributesmethodsfunctions ,以及 variables 。在每个文档字符串内,经过特殊格式化 Sections 都被解析并转换为reStrutiredText。

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

文档字符串部分

支持以下所有节标题:

  • Args (alias of Parameters)

  • Arguments (alias of Parameters)

  • Attention

  • Attributes

  • Caution

  • Danger

  • Error

  • Example

  • Examples

  • Hint

  • Important

  • Keyword Args (alias of Keyword Arguments)

  • Keyword Arguments

  • Methods

  • Note

  • Notes

  • Other Parameters

  • Parameters

  • Return (alias of Returns)

  • Returns

  • Raise (alias of Raises)

  • Raises

  • References

  • See Also

  • Tip

  • Todo

  • Warning

  • Warnings (alias of Warning)

  • Warn (alias of Warns)

  • Warns

  • Yield (alias of Yields)

  • Yields

谷歌VS NumPy

拿破仑支持两种样式的文档字符串: GoogleNumPy 。这两种风格之间的主要区别是,谷歌使用缩进来分隔部分,而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 Style:

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 文件.确保在中启用了“phinx.ext. napathon” 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
类型:
bool
默认:
True

解析为真 Google style 文档字符串。如果禁用对Google风格文档字符串的支持,则为假。

napoleon_numpy_docstring
类型:
bool
默认:
True

解析为真 NumPy style 文档字符串。False表示禁用对NumPy风格文档字符串的支持。

napoleon_include_init_with_doc
类型:
bool
默认:
False

与所列相符 __init___ 文档字符串与文档字符串类分开。假退回到Sphinx的默认行为,该行为考虑 __init___ doc字符串作为类文档的一部分。

If 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

确实包括私人成员(例如 _membername )在文档中使用文档字符串。假退回到Sphinx的默认行为。

If 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

确实包括特殊成员(例如 __membername__ )在文档中使用文档字符串。假退回到Sphinx的默认行为。

If 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

确实使用 .. admonition:: 的指令 ExampleExamples 路段使用错误 .. rubric:: 指令代替。一个可能比另一个看起来更好,这取决于使用的HTML主题。

NumPy style 代码段将按如下方式转换:

Example
-------
This is just a quick example

If True :

.. admonition:: Example

   This is just a quick example

If False :

.. rubric:: Example

This is just a quick example
napoleon_use_admonition_for_notes
类型:
bool
默认:
False

确实使用 .. admonition:: 性指令 Notes 路段使用错误 .. rubric:: 指令代替。

备注

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

napoleon_use_admonition_for_references
类型:
bool
默认:
False

确实使用 .. admonition:: 性指令 References 路段使用错误 .. rubric:: 指令代替。

napoleon_use_ivar
类型:
bool
默认:
False

确实使用 :ivar: 实例变量的角色。使用错误 .. attribute:: 指令代替。

NumPy style 代码段将按如下方式转换:

Attributes
----------
attr1 : int
    Description of `attr1`

If True :

:ivar attr1: Description of `attr1`
:vartype attr1: int

If False :

.. attribute:: attr1

   Description of `attr1`

   :type: int
napoleon_use_param
类型:
bool
默认:
True

确实使用a :param: 每个函数参数的作用。false使用一个 :parameters: 所有参数的角色。

NumPy style 代码段将按如下方式转换:

Parameters
----------
arg1 : str
    Description of `arg1`
arg2 : int, optional
    Description of `arg2`, defaults to 0

If True :

:param arg1: Description of `arg1`
:type arg1: str
:param arg2: Description of `arg2`, defaults to 0
:type arg2: :class:`int`, *optional*

If False :

:parameters: * **arg1** (*str*) --
               Description of `arg1`
             * **arg2** (*int, optional*) --
               Description of `arg2`, defaults to 0
napoleon_use_keyword
类型:
bool
默认:
True

确实使用a :keyword: 每个函数关键字参数的角色。false使用一个 :keyword arguments: 所有关键词的角色。

它的行为类似于 napoleon_use_param 。注意与docutils不同, :keyword::param: 将不会以相同的方式处理--将有一个单独的“关键字参数”部分,以与“参数”部分相同的方式呈现(如果可能,请输入链接)

napoleon_use_rtype
类型:
bool
默认:
True

确实使用 :rtype: 返回类型的角色。如果为假,则输出与描述内联的返回类型。

NumPy style 代码段将按如下方式转换:

Returns
-------
bool
    True if successful, False otherwise

If True :

:returns: True if successful, False otherwise
:rtype: bool

If False :

:returns: *bool* -- True if successful, False otherwise
napoleon_preprocess_types
类型:
bool
默认:
False

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

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

如果为True,则允许使用 PEP 526 类中的属性批注。如果某个属性记录在文档字符串中,但没有类型,并且在类体中有注释,则使用该类型。

Added in version 3.4.

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

添加要包括的自定义节的列表,展开已分析节的列表。

条目可以是字符串或元组,具体取决于用途:

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

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

  • 要创建一个显示方式类似于PARAMETERS或RETURNS节的自定义节,请传递一个包含自定义节名称和字符串值“PARAMS_STYLE”或“RETURNS_STYLE”的元组。

如果条目只是一个字符串,它将被解释为泛型部分的标题。如果条目是元组/列表/索引容器,则第一个条目是节的名称,第二个是要模拟的节键。如果第二个输入值为“PARAMS_STYLE”或“RETURNS_STYLE”,则自定义节的显示方式将与参数节或RETURNS节类似。

Added in version 1.8.

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