How do I find the default values ​​for a particular function argument in another Python function?


Let's suppose we have a function like this:

def myFunction(arg1='a default value'):

We can use introspection to find out the names of the arguments that myFunction() takes using myFunction.func_code.co_varnames, but how to find out the default value of arg1 (which is 'a default value' in the above example)?

As an alternative to rooting around in the attributes of the function you can use the inspect module for a slightly friendlier interface:

import inspect
spec = inspect.getargspec(myFunction)

Then spec is an ArgSpec object with attributes such as args and defaults:

ArgSpec(args=['arg1'], varargs=None, keywords=None, defaults=('a default value',))