LoginSignup
2
3

More than 3 years have passed since last update.

【python】関数の引数と返り値がわからないときの対処法

Posted at

pythonのコードを書いていて、関数の使い方がわからないときの対処法です。
いちいちブラウザで公式ドキュメントを確認する手間が面倒と感じていたので、「ちょっと確認したいだけ」って時に使えるテクニックです。

__doc__を表示する

結論から言ってしまえば、__doc__に記載されています。

具体的な使い方は、以下の通り。
例えば、numpyというパッケージのdot関数の使い方がわからなかったとします。
そんな時は、以下を実行することで、ドキュメントを確認することができます。

$ import numpy as np
$ print(np.dot.__doc__)

dot(a, b, out=None)

Dot product of two arrays. Specifically,

- If both `a` and `b` are 1-D arrays, it is inner product of vectors
  (without complex conjugation).

- If both `a` and `b` are 2-D arrays, it is matrix multiplication,
  but using :func:`matmul` or ``a @ b`` is preferred.

- If either `a` or `b` is 0-D (scalar), it is equivalent to :func:`multiply`
  and using ``numpy.multiply(a, b)`` or ``a * b`` is preferred.

- If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
  the last axis of `a` and `b`.

- If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
  sum product over the last axis of `a` and the second-to-last axis of `b`::

    dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

Parameters
----------
a : array_like
    First argument.
b : array_like
    Second argument.
out : ndarray, optional
    Output argument. This must have the exact kind that would be returned
    if it was not used. In particular, it must have the right type, must be
    C-contiguous, and its dtype must be the dtype that would be returned
    for `dot(a,b)`. This is a performance feature. Therefore, if these
    conditions are not met, an exception is raised, instead of attempting
    to be flexible.

Returns
-------
output : ndarray
    Returns the dot product of `a` and `b`.  If `a` and `b` are both
    scalars or both 1-D arrays then a scalar is returned; otherwise
    an array is returned.
    If `out` is given, then it is returned.

Raises
------
ValueError
    If the last dimension of `a` is not the same size as
    the second-to-last dimension of `b`.

See Also
--------
vdot : Complex-conjugating dot product.
tensordot : Sum products over arbitrary axes.
einsum : Einstein summation convention.
matmul : '@' operator as method with out parameter.
linalg.multi_dot : Chained dot product.

Examples
--------
>>> np.dot(3, 4)
12

Neither argument is complex-conjugated:

>>> np.dot([2j, 3j], [2j, 3j])
(-13+0j)

For 2-D arrays it is the matrix product:

>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
       [2, 2]])

>>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
>>> np.dot(a, b)[2,3,2,1,2,2]
499128
>>> sum(a[2,3,2,:] * b[1,2,:,2])
499128

こんな感じで、対話型モードの場合はコンソールに出力されます。

なるほど、引数にaとbとoutがあって、outでは何か色々設定ができるんだなとわかります。
返ってくる値の型も、ndarrayなんだなということがわかります。

こちらの関数の場合は、親切に計算の例まで書いてくれています。
引数aとbの内積を計算して、返す関数なんだな、ということがわかりました。

このようにして、関数の引数や返り値がわからないときは、簡単に確認することができます。

__doc__とは何なのか

__doc__を出力することで、関数の引数や返り値を確認できることはわかりました。
しかし、これらのドキュメントが保存されている__doc__とは何でしょうか。

その正体は、docstringという文字列です。

docstringとは何かと言うと、関数の使い方を利用者にも伝わるように残してあるコメントのことです。
もっと具体的に言えば、関数定義の最初に記載されたコメントのことです。

関数定義の最初に記載れたコメントは、python側で__doc__のattributeを設定しますので、__doc__として呼び出すことができます。

doc stringを書いてみよう

と言うわけで、簡単なdocstringを作ってみましょう。

以下のような関数を定義し、実行します。
関数の最初には、docstringを記載します。

def plus(a: int, b: int):
    '''
    Parameters
    ----------
        a : int
            First argument.
        b : int
            Second argument.
    Return
    ----------
        x : int
            a + b
    '''
    x: int = a + b

    return x

if __name__=='__main__':
    a, b = 10, 20
    print(plus(a,b))
    print(plus.__doc__)

このプログラムの実行結果は、以下の通りになります。

# python test.py
30

    Parameters
    ----------
        a : int
            First argument.
        b : int
            Second argument.
    Return
    ----------
        x : int
            a + b

__doc__に記載した内容が、きちんと表示されました!

2
3
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
2
3