【Python】ドックストリングの書き方【docstrings】

どうも、oyanです。
Pythonでプログラミングしていると、docstringsどう書くのがデファクトなの?
と疑問に思ったので調べてみました。
この記事は、Pythonのdocstringsの書き方についてまとめました。
開発時のコーディングルールの参考にしてみてください!

この記事で分かること

  • Pythonのdocstringsの書き方

docstringsとは何か?

docstringsは、「ドックストリング」「ドキュメント文字列」「ドキュメンテーション文字列」とも呼ばれます。
詳細は、以下の記事に書かれているので参考にしてみてください。
[Python入門]docstringの書き方

docstringsの書き方には大きく2つの流派がある

docstringsの書き方には大きく2つの流派があるようです。

  1. NumPyスタイル
  2. Googleスタイル

それでは、この2つのスタイルを纏めまくります!

Short Summary:簡単な1行の説明

def add(a, b):
   """The sum of two numbers.

   """
def add(a, b):
   """The sum of two numbers.

   """

Extended Summary: 複数行の詳細な概要

def add(a, b):
   """The sum of two numbers.

   (Extended Summary)
   """
def add(a, b):
   """The sum of two numbers.

   (Extended Summary)
   """

Parameters: 関数の引数

"""
Parameters
----------
x : type
    Description of parameter `x`.
y
    Description of parameter `y` (with type not specified)
"""
"""
Args:
  x (type): Description of parameter `x`.
  y: Description of parameter `y` (with type not specified)
"""

Returns: 関数の返り値

"""
Returns
-------
int
    Description of anonymous integer return value.
"""
"""
Returns
-------
err_code : int
    Non-zero value indicates error code, or zero on success.
err_msg : str or None
    Human readable error message, or None on success.
"""
"""
Returns:
  int: Description of anonymous integer return value.
"""

Raises: 例外

"""
Raises
------
LinAlgException
    If the matrix is not numerically invertible.
"""
"""
Raises:
  LinAlgException: If the matrix is not numerically invertible.
"""

See Also: 関連項目

"""
See Also
--------
average : Weighted average
"""
# なし

Notes: 備考。追加の説明。LaTeXも使える。

"""
Notes
----------
The FFT is a fast implementation of the discrete Fourier transform:
.. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n}
"""
"""
Note:
  The FFT is a fast implementation of the discrete Fourier transform:
  .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n}
"""

Examples: 使用例

"""
Examples
----------
>>> np.add(1, 2)
3
"""
"""
Example:
  >>> np.add(1, 2)
  3
"""

Attributes: クラスの属性

"""
Attributes
----------
x : float
    The X coordinate.
y : float
    The Y coordinate.
"""
"""
Attributes:
  x (float): The X coordinate.
  y (float): The Y coordinate.
"""

Methods: クラスのメソッド

"""
Methods
-------
colorspace(c='rgb')
    Represent the photo in the given colorspace.
gamma(n=1.0)
    Change the photo's gamma exposure.
"""
# なし