Spì Spì - 3 months ago 9
Python Question

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

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
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.

3.0 - 3.4 recommends inspect.getfullargspec(). See: https://docs.python.org/3.4/library/inspect.html#inspect.getargspec

3.5+ recommends inspect.signature(). See: https://docs.python.org/3.5/library/inspect.html#inspect.getargspec

Comments