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は、NumPyおよびGoogleスタイルの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を解釈します。これには、モジュールクラス属性メソッド関数、および変数のdocstringが含まれます。各docstring内では、特別にフォーマットされたセクションが解析され、reStructuredTextに変換されます。

すべての標準reStructuredTextフォーマットは、期待どおりに機能します。

Docstringのセクション

以下のすべてのセクションヘッダーがサポートされています。

  • Args (Parametersのエイリアス)

  • Arguments (Parametersのエイリアス)

  • 注意

  • 属性

  • 警告

  • 危険

  • エラー

  • ヒント

  • 重要

  • Keyword Args (Keyword Argumentsのエイリアス)

  • キーワード引数

  • メソッド

  • 注記

  • 注記

  • その他の引数

  • 引数

  • Return (Returnsのエイリアス)

  • 戻り値

  • Raise (Raisesのエイリアス)

  • 例外

  • 参考文献

  • 関連項目

  • ヒント

  • TODO

  • 警告

  • Warnings (Warningのエイリアス)

  • Warn (Warnsのエイリアス)

  • 警告

  • Yield (Yieldsのエイリアス)

  • Yields

Google vs NumPy

Napoleonは、GoogleNumPyの2つのスタイルのdocstringをサポートしています。2つのスタイルの主な違いは、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スタイルは短くてシンプルなdocstringを読みやすくする傾向があり、NumPyスタイルは長くて詳細なdocstringを読みやすくする傾向があります。

スタイルの選択は主に美的ですが、2つのスタイルを混在させるべきではありません。プロジェクトに1つのスタイルを選択し、それに一貫性を持たせてください。

関連項目

完全な例については、以下を参照してください。

型アノテーション

**PEP 484**では、Pythonコードで型を表現するための標準的な方法が導入されました。これは、docstringで直接型を表現する代わりに使用できます。**PEP 484**に従って型を表現することの利点の1つは、型チェッカーとIDEが静的コード分析にそれらを利用できることです。**PEP 484**は、**PEP 526**によって拡張され、変数(および属性)に注釈を付ける同様の方法が導入されました。

Python 3の型アノテーションを使用した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
    """

注記

Python 2/3互換アノテーションは現在Sphinxではサポートされておらず、ドキュメントには表示されません。

設定

以下は、napoleonで使用されるすべての設定とそのデフォルト値です。これらの設定は、Sphinxのconf.pyファイルで変更できます。“sphinx.ext.napoleon”が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スタイルのdocstringを解析するにはTrueにします。Googleスタイルのdocstringのサポートを無効にするにはFalseにします。*デフォルトはTrueです。*

napoleon_numpy_docstring

NumPyスタイルのdocstringを解析するにはTrueにします。NumPyスタイルのdocstringのサポートを無効にするにはFalseにします。*デフォルトはTrueです。*

napoleon_include_init_with_doc

__init___ docstringをクラスdocstringとは別にリスト表示するにはTrueにします。Sphinxのデフォルトの動作(__init___ docstringをクラスドキュメントの一部と見なす)に戻るにはFalseにします。*デフォルトはFalseです。*

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

ドキュメントにdocstringを含むプライベートメンバー(_membernameなど)を含めるにはTrueにします。Sphinxのデフォルトの動作に戻るにはFalseにします。*デフォルトはFalseです。*

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

ドキュメントに docstring を持つ特殊メンバー (例: __membername__) を含める場合は True です。 Sphinx のデフォルトの動作に戻す場合は False です。 *デフォルトは True です。*

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:: ディレクティブを使用する場合は True です。代わりに .. rubric:: ディレクティブを使用する場合は False です。使用されている HTML テーマによっては、一方の方がもう一方よりも見栄えが良くなる場合があります。 *デフォルトは False です。*

この 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

注記 セクションに .. admonition:: ディレクティブを使用する場合は True です。代わりに .. rubric:: ディレクティブを使用する場合は False です。 *デフォルトは False です。*

注記

単数の 注記 セクションは、常に .. note:: ディレクティブに変換されます。

napoleon_use_admonition_for_references

参考文献 セクションに .. admonition:: ディレクティブを使用する場合は True です。代わりに .. rubric:: ディレクティブを使用する場合は False です。 *デフォルトは False です。*

napoleon_use_ivar

インスタンス変数に :ivar: ロールを使用する場合は True です。代わりに .. attribute:: ディレクティブを使用する場合は False です。 *デフォルトは False です。*

この 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

各関数パラメーターに :param: ロールを使用する場合は True です。すべてのパラメーターに単一の :parameters: ロールを使用する場合は False です。 *デフォルトは True です。*

この 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

各関数のキーワード引数に :keyword: ロールを使用する場合は True です。すべてのキーワードに単一の :keyword arguments: ロールを使用する場合は False です。 *デフォルトは True です。*

これは、napoleon_use_param と同様に動作します。docutils とは異なり、:keyword::param: は同じようには扱われません。「パラメーター」セクションと同じ方法でレンダリングされる、個別の「キーワード引数」セクションが存在します(可能な場合は型リンクが作成されます)。

関連項目

napoleon_use_param

napoleon_use_rtype

戻り値の型に :rtype: ロールを使用する場合は True です。戻り値の型を説明と一緒にインラインで出力する場合は False です。 *デフォルトは True です。*

この 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

docstring 内の型の定義を参照として変換する場合は True です。デフォルトは *False* です。

バージョン 3.2.1 で追加されました。

バージョン 3.5 で変更されました: Google スタイルの docstring も前処理します。

napoleon_type_aliases

型名を他の名前または参照に変換するためのマッピングです。napoleon_use_param = True の場合にのみ機能します。 *デフォルトは None です。*

以下の場合

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

クラスで PEP 526 属性アノテーションを使用できるようにする場合は True です。属性が docstring に型なしでドキュメント化されており、クラス本体にアノテーションがある場合、その型が使用されます。

バージョン 3.4 で追加されました。

napoleon_custom_sections

解析されるセクションのリストを拡張するために、カスタムセクションのリストを追加します。 *デフォルトは None です。*

エントリは、意図に応じて文字列またはタプルのいずれかになります

  • カスタムの「汎用」セクションを作成するには、文字列を渡します。

  • 既存のセクションのエイリアスを作成するには、エイリアス名と元の名前を含むタプルをその順序で渡します。

  • パラメーターセクションまたは戻り値セクションのように表示されるカスタムセクションを作成するには、カスタムセクション名と文字列値「params_style」または「returns_style」を含むタプルを渡します。

エントリが文字列のみの場合、汎用セクションのヘッダーとして解釈されます。エントリがタプル/リスト/インデックス付きコンテナーの場合、最初のエントリはセクションの名前、2 番目はエミュレートするセクションキーです。2 番目のエントリ値が「params_style」または「returns_style」の場合、カスタムセクションはパラメーターセクションまたは戻り値セクションのように表示されます。

バージョン 1.8 で追加されました。

バージョン 3.5 で変更されました: params_stylereturns_style をサポートします