Python関数の説明の書き方(docstring)

Pythonで関数の説明を冒頭に記述するには、「ドキュメンテーション文字列(ドックストリング)」を使います。ドックストリングは関数のすぐ下に3つのダブルクォーテーション(""")を使って記述します。この部分には、関数の概要、引数、戻り値、関数の目的などを書くことができます。

以下はその構文の例です。

def 関数名(引数1, 引数2):
    """
    この関数の目的や説明をここに書きます。

    引数:
        引数1 (型): 引数1の説明
        引数2 (型): 引数2の説明

    戻り値:
        戻り値の型: 戻り値の説明
    """
    # 関数の処理
    処理結果 = 引数1 + 引数2
    return 処理結果

具体例

def add_numbers(a, b):
    """
    2つの数値を加算して結果を返す関数です。

    引数:
        a (int, float): 最初の数値
        b (int, float): 2つ目の数値

    戻り値:
        int, float: 2つの数値の合計
    """
    return a + b

上記の例では、add_numbers 関数の説明がドックストリングに記述されています。この説明は、help() 関数を使って外部から確認できます。

print(help(add_numbers))

英訳

In Python, to write a function description at the beginning of a function, you can use a “documentation string” (docstring). The docstring is written immediately below the function definition using three double quotes ("""). This section can include a summary of the function, its arguments, return values, and the function’s purpose.

Below is the syntax example:

def function_name(arg1, arg2):
    """
    Write the purpose and description of the function here.

    Args:
        arg1 (type): Description of argument 1
        arg2 (type): Description of argument 2

    Returns:
        return_type: Description of the return value
    """
    # Function logic
    result = arg1 + arg2
    return result

Specific Example

def add_numbers(a, b):
    """
    This function adds two numbers and returns the result.

    Args:
        a (int, float): The first number
        b (int, float): The second number

    Returns:
        int, float: The sum of the two numbers
    """
    return a + b

In the above example, the description of the add_numbers function is written in the docstring. You can check the description externally using the help() function:

print(help(add_numbers))

重要単語と熟語

  • docstring: 関数の説明文として使われる文字列。3つのダブルクォーテーションで囲まれる。
  • args: 引数の略語で、関数に渡されるデータを指す。
  • returns: 関数が返す値やその説明に使われる。

コメントする