0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】docstringについて

Posted at

docstringとは

Pythonでは、関数/型の仕様をコード内でコメントとして残す仕組みを用意しています。
この機能によって、コードの仕様をSphinxなどのツールによってドキュメント化したり、IDEやエディタで簡単に確認することができます。

docstringは単に```~```や、"""~"""で記述する複数行のコメントです。
記述場所は限定されており、def/clssブロックの先頭に記述します。
決まった形式はないのですが、これから紹介する3つがよく使われる形式になります。

Googleスタイル

def add(x: int, y: int) -> int:
    """Add two integers.

    Args:
        x (int): The first number.
        y (int): The second number.

    Returns:
        int: The sum of x and y.
    """
    return x + y

メリット:

  • 見た目がシンプルで読みやすい。
  • 人間にとって理解しやすい形式。
  • 多くのツール(例:Sphinxの拡張 sphinx.ext.napoleon)でそのまま使える。

デメリット:

  • 厳密な構文ではないため、解析ツール(型チェックや自動ドキュメント生成)でエラー検出しづらい。
  • NumPyスタイルより複雑な型情報や例外の記述がしづらい。

NumPyスタイル

def add(x: int, y: int) -> int:
    """Add two integers.

    Parameters
    ----------
    x : int
        The first number.
    y : int
        The second number.

    Returns
    -------
    int
        The sum of x and y.
    """
    return x + y

メリット:

  • 表形式に近く、視認性が高い(特に科学・数値計算系の関数で読みやすい)。
  • 複数の戻り値や配列形状などの説明がしやすい。
  • Sphinxやnumpydocでのドキュメント生成に強い。

デメリット:

  • 英文のようではなく、少し機械的で堅い印象。
  • 項目のインデントやアンダーラインなど書式のルールがやや多い。

reStructuredText(reST)スタイル

def add(x: int, y: int) -> int:
    """Add two integers.

    :param x: The first number.
    :type x: int
    :param y: The second number.
    :type y: int
    :return: The sum of x and y.
    :rtype: int
    """
    return x + y

メリット:

  • Sphinxが標準対応しているスタイル(正式サポート)。
  • 明示的なタグ(:param: など)があるので、機械的に解析しやすい。
  • 厳密な構造を必要とする大規模プロジェクト向き。

デメリット

  • 可読性が低く、書くのが面倒。
  • タグが多いため、短い関数には冗長に感じる。

参考文献

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?