33
24

More than 3 years have passed since last update.

Pythonのドキュメントコメント(Docstrings)の書き方

Posted at

Pythonドキュメントコメント

Pythonのドキュメントコメント(Docstrings)の書き方です。
どうも、派閥?流派?があるようです。

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

Short Summary:簡単な1行説明。名前とか

NumPyスタイル.py
def add(a, b):
   """The sum of two numbers.

   """
Googleスタイル.py
def add(a, b):
   """The sum of two numbers.

   """

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

NumPyスタイル.py
def add(a, b):
   """The sum of two numbers.

   (Extended Summary)
   """
Googleスタイル.py
def add(a, b):
   """The sum of two numbers.

   (Extended Summary)
   """

Parameters: 関数の引数

NumPyスタイル.py
"""
Parameters
----------
x : type
    Description of parameter `x`.
y
    Description of parameter `y` (with type not specified)
"""
Googleスタイル.py
"""
Args:
  x (type): Description of parameter `x`.
  y: Description of parameter `y` (with type not specified)
"""

Returns: 関数の返り値

NumPyスタイル.py
"""
Returns
-------
int
    Description of anonymous integer return value.
"""
NumPyスタイル.py
"""
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.
"""
Googleスタイル.py
"""
Returns:
  int: Description of anonymous integer return value.
"""

Raises: 例外

NumPyスタイル.py
"""
Raises
------
LinAlgException
    If the matrix is not numerically invertible.
"""
Googleスタイル.py
"""
Raises:
  LinAlgException: If the matrix is not numerically invertible.
"""

See Also: 関連項目

NumPyスタイル.py
"""
See Also
--------
average : Weighted average
"""
Googleスタイル.py
# なし

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

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

Examples: 使用例

NumPyスタイル.py
"""
Examples
----------
>>> np.add(1, 2)
3
"""
Googleスタイル.py
"""
Example:
  >>> np.add(1, 2)
  3
"""

Attributes: クラスの属性

NumPyスタイル.py
"""
Attributes
----------
x : float
    The X coordinate.
y : float
    The Y coordinate.
"""
Googleスタイル.py
"""
Attributes:
  x (float): The X coordinate.
  y (float): The Y coordinate.
"""

Methods: クラスのメソッド

NumPyスタイル.py
"""
Methods
-------
colorspace(c='rgb')
    Represent the photo in the given colorspace.
gamma(n=1.0)
    Change the photo's gamma exposure.
"""
Googleスタイル.py
# なし
33
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
24