docstring

投稿者: | 2022-12-25

参考HP:Python入門]docstringの書き方

目次

書き方

  • docstring(ドキュストリング)は、モジュールのソースコード(.pyファイル)の先頭、class や def 文の直後に書かれた複数行のコメントのこと
  • このコメントからドキュメントを生成することもできる
  • docstring はトリプルクォート(”””)で囲む & 必ずダブルクォートを使用する
  • 1行目はサマリ、ピリオドで終わる
  • 1行あたり72文字
  • r””” ではじめると RAW docstring になり、バックスラッシュを含めることが出来る
  • サマリは命令形で記述する。動詞ではじめる
  • 1行目にサマリ、2行目は空行、3行目以降に詳細コメント
  • 自作関数の場合、それを import すればインタープリター上で docstring の内容を確認できる
    • >>> help(test.func)   ← test.py 上の func 関数

サンプル(関数)

# 1行のdocstring
def add(x, y):
    """Returs sum of x and y."""
    return x + y

# 複数行のdocstring
def add(x, y):
    """Returns sum of x and y.

    Parameters:
    ------------
    x: int
        operand1 of addition
    y: int
        operand2 of addition

    Returns:
    ------------
    int
        sum of x and y
    """
    
    return x + y

サンプル(モジュール)

__doc__

docstring は、__doc__ に格納されている

以下は、print の docstring

書き方(詳細)

docstringのスタイル(勉強になる)

Google Python Style Guide」の「3.8 Comments and Docstrings

numpydoc docstring guide