How can I read a function's signature including default argument values?

Spì picture Spì · Apr 20, 2010 · Viewed 71.4k times · Source

Given a function object, how can I get its signature? For example, for:

def myMethod(firt, second, third='something'):
    pass

I would like to get "myMethod(firt, second, third='something')".

Answer

unutbu picture unutbu · Apr 20, 2010
import inspect

def foo(a, b, x='blah'):
    pass

print(inspect.getargspec(foo))
# ArgSpec(args=['a', 'b', 'x'], varargs=None, keywords=None, defaults=('blah',))

However, note that inspect.getargspec() is deprecated since Python 3.0.

Python 3.0--3.4 recommends inspect.getfullargspec().

Python 3.5+ recommends inspect.signature().