How to find out the default values ​​for a particular function argument in another function in Python?

Suppose we have a function like this:

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

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

+8
source share
3 answers

As an alternative to using function attributes, you can use the inspect module for a more user-friendly interface:

For Python 3.x interpreters:

 import inspect spec = inspect.getfullargspec(myFunction) 

Then spec is a FullArgSpec object with attributes such as args and defaults :

 FullArgSpec(args=['arg1'], varargs=None, varkw=None, defaults=('a default value',), kwonlyargs=[], kwonlydefaults=None, annotations={}) 

Some of these attributes are not available in Python 2, so if you have to use the old version of inspect.getargspec(myFunction) , you will get a similar value without Python 3 functions ( getargspec also works on Python 3, but not recommended with Python 3.0 so don't use )

 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',)) 
+9
source

If you define the function f as follows:

 >>> def f(a=1, b=True, c="foo"): ... pass ... 

in Python 2, you can use:

 >>> f.func_defaults (1, True, 'foo') >>> help(f) Help on function f in module __main__: f(a=1, b=True, c='foo') 

whereas in Python 3 it is:

 >>> f.__defaults__ (1, True, 'foo') >>> help(f) Help on function f in module __main__: f(a=1, b=True, c='foo') 
+9
source

My bad. Of course, there is myFunction.func_defaults .

0
source

All Articles