Let's say I have a function:
def foo(a=None, b=None, c=None): return "a:%s, b:%s, c:%s" % (a, b, c)
I have a dictionary with some (or none) of the arguments above, but also with keys that are not named arguments in the function, e.g.:
d = {'a': 1, 'x': 4, 'b': 2, 'y': 5}
If I call the following I will get an error, because 'x' and 'y' are not keyword arguments in the foo function.
foo(**d) # error
Is there an elegant way of passing the arguments from a dictionary to a function, but only those values with keys that match the function arguments.
Please correct me if my argument/parameter terminology is off.
In python functions, we can pack or unpack function arguments. Unpacking: During function call, we can unpack python list/tuple/range/dict and pass it as separate arguments. * is used for unpacking positional arguments.
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
Keyword-only arguments are another attribute of Python functions that have been available since Python 3.0. These arguments are specified using the '*' marker. They prompt the user to state the keyword used in the already defined function when making a call to the same function.
>>> range ( * args) # call with arguments unpacked from a list. [ 3 , 4 , 5 ] Packing. When we don't know how many arguments need to be passed to a python function, we can use Packing to pack all arguments in a tuple.
def foo(a = None, b=None, c=None,**extras): return "a:%s, b:%s, c:%s" % (a, b, c)
here the **extras
will collect all the extra named/keyword arguments.
@Ashwini Chaudhary has a very pythonic way of solving your problem. However, it requires changing the signature of your foo
function.
If you don't want to change your function signature, you can use introspection to find out what arguments your function expects:
arg_count = foo.func_code.co_argcount args = foo.func_code.co_varnames[:arg_count] args_dict = {} for k, v in d.iteritems(): if k in args: args_dict[k] = v foo(**args_dict)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With