はじめに
Pythonでは関数やクラス、モジュールなどにドキュメント文字列(docstring)を追加することでコードの理解を助け、保守性を向上させることができます。
この記事ではdocstringの基礎から記述方法、便利なVSCodeの拡張機能について解説します。
docstringとは
docstringは、コードの構造体(関数、クラス、モジュールなど)に関連する説明を含む文字列です。
""" """で囲まれたコメントを記述することで、Pythonのhelp()関数やIDEがこの情報を活用でき、実装時にIDEが使用するメソッドなどでdocstringを表示してくれるためコードの理解が容易になります。
docstringがない場合
docstringがある場合
docstringが有ることで関数を使い方がよく分かりますね。
docstringのスタイル
Pythonにはいくつかの標準的なdocstringスタイルがあります。
一般的なものは、以下のスタイルです。
- Googleスタイル
- NumPyスタイル
- Sphinxスタイル(reStructuredText)
個人的にGoogleスタイルが好みでよく使用しており、今回はGoogleスタイルを主に解説します。
docstringの書き方(Googleスタイル)
サンプルコードはGoogleのスタイルガイドから引用しています。
モジュールのdocstring
モジュールの冒頭には、そのモジュールの目的と機能を説明するdocstringを記述します。
- モジュールの全体的な目的
- 使用されるクラスや関数の概要
- 使用例
サンプルコード
"""A one-line summary of the module or program, terminated by a period.
Leave one blank line.  The rest of this docstring should contain an
overall description of the module or program.  Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.
Typical usage example:
  foo = ClassFoo()
  bar = foo.FunctionBar()
"""
関数およびメソッドのdocstring
関数やメソッドでは以下を記述します
- 概要
- 引数(Args)
 各引数名、型、説明を記述
- 戻り値(Returns)
 戻り値の型と内容を記述(戻り値がNoneのみを返す場合は不要)
- 例外(Raises)
 発生する例外を記載
関数やメソッドが以下に当てはまる場合は特にdocstringの記載する必要性が高いです。
- モジュールやクラスの外部からアクセス可能な関数やメソッド
- 処理内容が直感的に分かりにくい場合(アルゴリズムや複雑な処理を含む場合)
- サイズが大きい(関数やメソッドが大規模で多くの処理を含む)場合
サンプルコード
def fetch_smalltable_rows(
    table_handle: smalltable.Table,
    keys: Sequence[bytes | str],
    require_all_keys: bool = False,
) -> Mapping[bytes, tuple[str, ...]]:
    """Fetches rows from a Smalltable.
    Retrieves rows pertaining to the given keys from the Table instance
    represented by table_handle.  String keys will be UTF-8 encoded.
    Args:
        table_handle: An open smalltable.Table instance.
        keys: A sequence of strings representing the key of each table
          row to fetch.  String keys will be UTF-8 encoded.
        require_all_keys: If True only rows with values set for all keys will be
          returned.
    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:
        {b'Serak': ('Rigel VII', 'Preparer'),
         b'Zim': ('Irk', 'Invader'),
         b'Lrrr': ('Omicron Persei 8', 'Emperor')}
        Returned keys are always bytes.  If a key from the keys argument is
        missing from the dictionary, then that row was not found in the
        table (and require_all_keys must have been False).
    Raises:
        IOError: An error occurred accessing the smalltable.
    """
クラスのdocstring
クラスでは以下を記述します:
- 概要
- 属性(Attributes): インスタンス変数の説明を記述
class SampleClass:
    """Summary of class here.
    Longer class information...
    Longer class information...
    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """
    def __init__(self, likes_spam: bool = False):
        """Initializes the instance based on spam preference.
        Args:
          likes_spam: Defines if instance exhibits this preference.
        """
        self.likes_spam = likes_spam
        self.eggs = 0
    @property
    def butter_sticks(self) -> int:
docstringを書く際におすすめなVSCode拡張機能
VSCodeにはdocstringを書くときに便利な拡張機能があるため紹介します。
autoDocstringという拡張機能をダウンロードすることで、関数やクラスに"""を入力し、Enterキーを押すだけ(右クリックからGenerate Docstringでも呼び出し可能)で引数や戻り値に関するテンプレートが自動生成されるため非常に便利です。
docstringのテンプレート自動生成実演
まとめ
docstringは、Pythonコードの可読性とメンテナンス性を大幅に向上させる強力な手段です。
ぜひ実装コードに取り入れてみてください!




