LoginSignup
23
11

More than 5 years have passed since last update.

python で関数の引数の名前を取得する方法

Posted at

結論

関数名.__code__.co_varnames[:関数名.__code__.co_argcount]

とすると取得できます

実例

以下のようなテストコードを用意しました

test
def fnc3(a, b, c):
    d = 0
    return a + b + c

arg_names = fnc3.__code__.co_varnames[:fnc3.__code__.co_argcount]
print(arg_names)
$ python test.py
('a', 'b', 'c')

きちんと取得できていますね

ちなみに

__code__.co_varnamesは単にその関数内で使用されている変数を列挙するだけなので

arg_names = fnc3.__code__.co_varnames

とすると、関数内で使用されているdくんも取得してしまいます

$ python test.py
('a', 'b', 'c', 'd')

余談

python2ではinspect.getargspec
python3ではinspect.signature
というものを本来使って情報を取得するらしい

しかし、こちらのほうが単純なので、今後はこちらを使用する

23
11
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
23
11