Numpy Style の docstring

リファクタリングしたり、他の人に移譲する時にドキュメントがあったほうが良いよなと思い、Numpy Styleのdocstringを調べた。


numpydoc.readthedocs.io

記述例

def add(a: float, b: float=0.0) -> float:
    """
    Add two floats.

    Parameters
    ----------
    a : float
        Description of parameter `a`.
    b : float, default 0.0
        Description of parameter `b`.

    Returns
    -------
    float
        The sum of two floats.

    Yields
    ------
    Type
        Description of generated value.

    Receives
    --------
    Type
        Explaination of parameters passed to a generator's .send() method.

    Raises
    ------
    Exception
        Description of errors.

    See Also
    --------
        Related functions witch users may not be aware of, etc...

    Notes
    -----
        Additional information.

    Examples
    --------
    >>> add(3.0, 4.0)
    7.0

    >>> add(1.0)
    1.0
    """

    return a + b



class MyClass:
    """
    MyClass

    Attributes
    ----------
    id : int
        Identfier.
    value : float
        Value.
    name : str
        Name.

    Methods
    -------
    get_id()
        Return its id.
    set_value(value)
        Set value
    """
    def __init__(self, id: int, value: float, name: str) -> None:
        self.id: int = id
        self.value: float = value
        self.name: str = name

    def get_id(self) -> int:
        """
        Return its id.

        Returns
        -------
        int
            id
        
        Examples
        --------
        >>> A = MyClass(2, 3.0, 'name')
        >>> A.get_id()
        2
        """
        return self.id

    
    def set_value(self, value: float) -> None:
        """
        Set value.

        Parameters
        ----------
        value : float
            an float value to set.
        
        Examples
        --------
        >>> A = MyClass(0, 0.0, 'name')
        >>> A.value
        0.0
        >>> A.set_value(3.0)
        >>> A.value
        3.0
        """
        self.value = value

    
if __name__ == '__main__':
    import doctest
    doctest.testmod()

Sections

アンダーラインハイフンでセクションを区切る。
Short Summary
一行の簡単な説明。
Parameters
パラメータ名 : 型(, default デフォルト値)
パラメータの説明。
Returns

戻り値の説明。
Raises
Raiseしうる例外の説明。
See Also
ユーザーが知覚して無さそうな関連した関数とかの情報。
Notes
補足説明。
Examples
実行例。

所感

VSCodeとかだとホバーした時にドキュメントが表示されて便利。
確かdocstringからドキュメントを生成するツールもあったはず。

ただ明らかに1ファイルの文字数は増えていて、逆に読みにくくならないか心配。