Reputation: 5243
Using python 2.4, I'm attempting to identify, at runtime, which of an arbitrary function's arguments have default values. Unfortunately, although I can find what the default values are, I can't seem to get a handle on which parameters they correspond to. For example:
def foo(a, b, c=5):
return a + b + c
import inspect
inspect.getargspec(foo) # output is: (['a', 'b', 'c'], None, None, (5,))
The output of getargspec
is clearer in python 2.6, which returns a named tuple:
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=(5,))
Python obviously has enough information to accomplish the task during execution. How can I get at it?
Upvotes: 4
Views: 155
Reputation: 879143
Arguments with default values must follow arguments without default values.
So if there are any defaults, they must correspond to the arguments at the tail end of args
.
In your case, args=['a','b','c']
, and defaults=(5,)
. So the default must correspond to c
.
import inspect
def foo(a, b, c=5):
return a + b + c
def show_defaults(f):
args, varargs, varkw, defaults = inspect.getargspec(f)
if defaults:
for arg, default in zip(args[-len(defaults):], defaults):
print('{a} = {d}'.format(a=arg,d=default))
show_defaults(foo)
# c = 5
Upvotes: 6
Reputation: 14410
From the documentation, it discusses the value for defaults
:
if this tuple has n elements, they correspond to the last n elements listed in args.
In your case defaults
contains one value and corresponds to the last element listed in args
, which is c
.
Upvotes: 3