Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking keyword arguments, but only the ones that match the function

Tags:

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.

like image 828
Mads Skjern Avatar asked Jun 16 '12 17:06

Mads Skjern


People also ask

What is unpacking arguments in Python?

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.

What are keyword arguments in function?

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.

What is a keyword only argument?

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.

What is packing and unpacking arguments in Python?

>>> 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.


2 Answers

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.

like image 105
Ashwini Chaudhary Avatar answered Sep 23 '22 11:09

Ashwini Chaudhary


@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) 
like image 39
Rodrigue Avatar answered Sep 23 '22 11:09

Rodrigue