N
Noah
Is there a simple way to get a dictionary of
argument names and their default values for
a method or function? I came up with one solution, but
I feel like Python must have a simpler way.
Python provide a way to get a sequence of
argument names and a different way to get a
sequence of default argument values. Since
default values have to come at the end of an
argument list you can match up the values in the
default values sequence to the values in the
argument list sequence.
The following seems to work on both functions and methods::
def func_arg_defaults_dict (func):
default_dict = {}
if func.func_defaults is not None:
da_start = len(func.func_code.co_names) -
len(func.func_defaults)
for i in range(len(func.func_defaults)):
arg_name = func.func_code.co_names[da_start+i]
arg_value = func.func_defaults
default_dict [arg_name] = arg_value
return default_dict
def foo (f1, f2, f3, f4='F4', a5='F5'):
print f1, f2, f3, f4, f5
class fu:
def foo (self, m1, m2, m3, m4='M4', m5='M5'):
print m1, m2, m3, m4, m5
f = fu()
# test function
print func_arg_defaults_dict (foo)
# test method
print func_arg_defaults_dict (f.foo)
Running the script prints this::
{'f4': 'F4', 'f5': 'F5'}
{'m5': 'M5', 'm4': 'M4'}
Is func_arg_defaults_dict() reasonable? It seems a bit convoluted.
I hope there is a more obvious way.
Yours,
Noah
argument names and their default values for
a method or function? I came up with one solution, but
I feel like Python must have a simpler way.
Python provide a way to get a sequence of
argument names and a different way to get a
sequence of default argument values. Since
default values have to come at the end of an
argument list you can match up the values in the
default values sequence to the values in the
argument list sequence.
The following seems to work on both functions and methods::
def func_arg_defaults_dict (func):
default_dict = {}
if func.func_defaults is not None:
da_start = len(func.func_code.co_names) -
len(func.func_defaults)
for i in range(len(func.func_defaults)):
arg_name = func.func_code.co_names[da_start+i]
arg_value = func.func_defaults
default_dict [arg_name] = arg_value
return default_dict
def foo (f1, f2, f3, f4='F4', a5='F5'):
print f1, f2, f3, f4, f5
class fu:
def foo (self, m1, m2, m3, m4='M4', m5='M5'):
print m1, m2, m3, m4, m5
f = fu()
# test function
print func_arg_defaults_dict (foo)
# test method
print func_arg_defaults_dict (f.foo)
Running the script prints this::
{'f4': 'F4', 'f5': 'F5'}
{'m5': 'M5', 'm4': 'M4'}
Is func_arg_defaults_dict() reasonable? It seems a bit convoluted.
I hope there is a more obvious way.
Yours,
Noah