ドキュメンテーション

Pythonパッケージ開発

James Fulton

Climate informatics researcher

なぜドキュメントを書くのか

  • 利用者がコードを使いやすくする
  • それぞれを記載
    • 関数
    • クラス
    • クラスメソッド
import numpy as np
help(np.sum)
...
sum(a, axis=None, dtype=None, out=None)
    Sum of array elements over a given axis.

    Parameters
    ----------
    a : array_like
        Elements to sum.
    axis : None or int or tuple of ints, optional
        Axis or axes along which a sum is performed.  
        The default, axis=None, will sum all of the 
        elements of the input array.
...
Pythonパッケージ開発

なぜドキュメントを書くのか

  • 利用者がコードを使いやすくする
  • それぞれを記載
    • 関数
    • クラス
    • クラスメソッド
import numpy as np
help(np.array)
...
    array(object, dtype=None, copy=True)

    Create an array.

    Parameters
    ----------
    object : array_like
        An array, any object exposing the array 
        interface ...
    dtype : data-type, optional
        The desired data-type for the array. 
    copy : bool, optional
        If true (default), then the object is copied.
...
Pythonパッケージ開発

なぜドキュメントを書くのか

  • 利用者がコードを使いやすくする
  • それぞれを記載
    • 関数
    • クラス
    • クラスメソッド
import numpy as np
x = np.array([1,2,3,4])
help(x.mean)
...
mean(...) method of numpy.ndarray instance
    a.mean(axis=None, dtype=None, out=None)

    Returns the average of the array elements 
    along given axis.

    Refer to `numpy.mean` for full documentation.
...
Pythonパッケージ開発

関数のドキュメント化

def count_words(filepath, words_list):

""" ... """
Pythonパッケージ開発

関数のドキュメント化

def count_words(filepath, words_list):

"""これらの語が出現する合計回数を数える。"""
Pythonパッケージ開発

関数のドキュメント化

def count_words(filepath, words_list):

"""これらの語が出現する合計回数を数える。 指定パスのテキストファイルで数える。 """
Pythonパッケージ開発

関数のドキュメント化

def count_words(filepath, words_list):

"""これらの語が出現する合計回数を数える。 指定パスのテキストファイルで数える。 [filepath と words_list の説明] [返り値] """
Pythonパッケージ開発

ドキュメントのスタイル

Google スタイル

"""要約行。

関数の詳細説明。

Args:
    arg1 (int): arg1 の説明
    arg2 (str): arg2 の説明

NumPy スタイル

    """要約行。

    関数の詳細説明。

    Parameters
    ----------
    arg1 : int
        arg1 の説明 ...

    Returns
    ----------
    numpy.ndarray

reStructuredText スタイル

    """要約行。

    関数の詳細説明。

    :param arg1: arg1 の説明
    :type arg1: int
    :param arg2: arg2 の説明
    :type arg2: str

Epytext スタイル

"""要約行。

  関数の詳細説明。

  @type arg1: int
  @param arg1:  arg1 の説明
  @type arg2: str
  @param arg2: arg2 の説明
Pythonパッケージ開発

NumPy ドキュメントスタイル

科学系 Python パッケージで一般的:

  • numpy
  • scipy
  • pandas
  • sklearn
  • matplotlib
  • dask
  • など
Pythonパッケージ開発

NumPy ドキュメントスタイル

import scipy
help(scipy.percentile)
percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear')
    Compute the q-th percentile of the data along the specified axis.

    Returns the q-th percentile(s) of the array elements.


Parameters ----------
a : array_like
Input array or object that can be converted to an array.

他の型例: int, float, bool, str, dict, numpy.array など

Pythonパッケージ開発

NumPy ドキュメントスタイル

import scipy
help(scipy.percentile)
percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear')
    ...
    Parameters
    ----------
    ...
    axis : {int, tuple of int, None}
    ...
    interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
  • 適切なら複数の型を列挙
  • 有効値が限られる場合は受け入れ可能値を列挙
Pythonパッケージ開発

NumPy ドキュメントスタイル

import scipy
help(scipy.percentile)
percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear')
    ...
    Returns
    -------
    percentile : scalar or ndarray
        If `q` is a single percentile and `axis=None`, then the result
        is a scalar. If multiple percentiles are given, first axis of
        the result corresponds to the percentiles...
    ...
Pythonパッケージ開発

NumPy ドキュメントスタイル

その他のセクション

  • Raises
  • See Also
  • Notes
  • References
  • Examples
1 https://numpydoc.readthedocs.io/en/latest/format.html
Pythonパッケージ開発

テンプレートとスタイル変換

  • pyment で docstring を自動生成
  • ターミナルから実行
  • 対応スタイル
    • Google
    • Numpydoc
    • reST(reStructuredText)
    • Javadoc(epytext)
  • スタイル間の変換も可能
Pythonパッケージ開発

テンプレートとスタイル変換

pyment -w -o numpydoc textanalysis.py
def count_words(filepath, words_list):
    # Open the text file
    ...
    return n
  • -w - 上書き
  • -o numpydoc - NumPy スタイルで出力
Pythonパッケージ開発

テンプレートとスタイル変換

pyment -w -o numpydoc textanalysis.py
def count_words(filepath, words_list):
    """

    Parameters
    ----------
    filepath :

    words_list :


    Returns
    -------
    type
    """
Pythonパッケージ開発

Google スタイルへ変換

pyment -w -o google textanalysis.py
def count_words(filepath, words_list):
    """これらの語が出現する合計回数を数える。

    指定パスのテキストファイルで数える。

    Parameters
    ----------
    filepath : str
        テキストファイルへのパス。
    words_list : list of str
        これらの語の出現回数を集計。

    Returns
    -------

    """
Pythonパッケージ開発

Google スタイルへ変換

pyment -w -o google textanalysis.py
def count_words(filepath, words_list):
    """これらの語が出現する合計回数を数える。

    指定パスのテキストファイルで数える。

    Args:
      filepath(str): テキストファイルへのパス。
      words_list(list of str): これらの語の出現回数を集計。

    Returns:


    """
Pythonパッケージ開発

パッケージ、サブパッケージ、モジュールのドキュメント

mysklearn/__init__.py

"""
Python 用の線形回帰
============================

mysklearn は、Python で線形回帰を実装する
完全なパッケージです。 
"""

mysklearn/preprocessing/__init__.py

"""
標準的な前処理を行うサブパッケージ。
"""

 

mysklearn/preprocessing/normalize.py

"""
データを正規化するモジュール。
"""
Pythonパッケージ開発

Passons à la pratique !

Pythonパッケージ開発

Preparing Video For Download...