sphinx.ext.napoleon – NumPy 和 Google 風格 docstring 支援

模組作者:Rob Ruana

於版本 1.3 新增。

概觀

您是否厭倦了撰寫看起來像這樣的 docstring

: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 很棒,但它會建立視覺上密集、難以閱讀的 docstring。將上面的雜亂與根據 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 風格的 docstring - Khan Academy 推薦的風格。

Napoleon 是一個預處理器,它會解析 NumPyGoogle 風格的 docstring,並在 Sphinx 嘗試解析它們之前將其轉換為 reStructuredText。這發生在 Sphinx 處理文件的中間步驟中,因此它不會修改您實際原始碼檔案中的任何 docstring。

開始使用

  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
    

Docstring

Napoleon 會解譯 autodoc 可以找到的每個 docstring,包括 modulesclassesattributesmethodsfunctionsvariables 上的 docstring。在每個 docstring 內部,特別格式化的區段會被解析並轉換為 reStructuredText。

所有標準 reStructuredText 格式仍可如預期般運作。

Docstring 區段

支援以下所有區段標頭

  • Args (Parameters 的別名)

  • Arguments (Parameters 的別名)

  • 注意

  • 屬性

  • 注意

  • 危險

  • 錯誤

  • 範例

  • 範例

  • 提示

  • 重要

  • Keyword Args (Keyword Arguments 的別名)

  • Keyword Arguments

  • 方法

  • 注意

  • 注意事項

  • Other Parameters

  • Parameters

  • Return (Returns 的別名)

  • Returns

  • Raise (Raises 的別名)

  • Raises

  • 參考文獻

  • See Also

  • 提示

  • 待辦事項

  • 警告

  • Warnings (Warning 的別名)

  • Warn (Warns 的別名)

  • Warns

  • Yield (Yields 的別名)

  • Yields

Google vs NumPy

Napoleon 支援兩種風格的 docstring: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 風格往往使用更多水平空間。對於簡短而簡單的 docstring,Google 風格往往更易於閱讀,而對於冗長而深入的 docstring,NumPy 風格往往更易於閱讀。

風格的選擇很大程度上是美學上的,但不應混合使用這兩種風格。為您的專案選擇一種風格,並保持一致。

類型註解

PEP 484 引入了一種在 Python 程式碼中表達類型的標準方式。這是直接在 docstring 中表達類型的替代方法。根據 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

docstring 中具有類型的 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 風格 docstring。False 以停用 Google 風格 docstring 的支援。

napoleon_numpy_docstring
類型:
bool
預設值:
True

True 以解析 NumPy 風格 docstring。False 以停用 NumPy 風格 docstring 的支援。

napoleon_include_init_with_doc
類型:
bool
預設值:
False

True 以將 __init___ docstring 與類別 docstring 分開列出。False 以回復為 Sphinx 的預設行為,後者將 __init___ docstring 視為類別文件的一部分。

如果為 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 以在文件中包含具有 docstring 的私有成員(如 _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 以在文件中包含具有 docstring 的特殊成員(如 __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 以將 docstring 中的類型定義轉換為參考。

於版本 3.2.1 新增。

在版本 3.5 中變更:也預處理 Google 風格的 docstring。

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 屬性註解。如果屬性在 docstring 中有文件記錄但沒有類型,並且在類別主體中具有註解,則會使用該類型。

於版本 3.4 新增。

napoleon_custom_sections
類型:
Sequence[str | tuple[str, str]] | None
預設值:
None

新增要包含的自訂區段清單,以擴充已解析區段的清單。

項目可以是字串或元組,具體取決於意圖

  • 若要建立自訂「通用」區段,只需傳遞字串即可。

  • 若要為現有區段建立別名,請傳遞包含別名和原始區段的元組,順序如下。

  • 若要建立自訂區段,使其顯示方式與 parameters 或 returns 區段類似,請傳遞包含自訂區段名稱和字串值「params_style」或「returns_style」的元組。

如果項目只是字串,則會將其解譯為通用區段的標頭。如果項目是元組/清單/索引容器,則第一個項目是區段的名稱,第二個項目是要模擬的區段金鑰。如果第二個項目值為「params_style」或「returns_style」,則自訂區段將以類似 parameters 區段或 returns 區段的方式顯示。

於版本 1.8 新增。

在版本 3.5 中變更:支援 params_stylereturns_style