Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple kwargs in a function call?

Tags:

python

I have a simple function which is called like this:

arbitrary_function(**kwargs1, **kwargs2, **kwargs3)

It seems to compile fine on my local installation (python 3.5.1) but throws a SyntaxError when I compile it on a docker with python 3.4.5.

I'm not too sure why this behavior is present. Are multiple kwargs not allowed? Should I combine them before passing to function? It is more convenient to pass them individually, for example:

plot(**x_axis_params, **y_axis_params, **plot_params)

instead of

params = dict()

for specific_param in [x_axis_params, y_axis_params, plot_params]:    
    params.update(specific_param)

plot(**params)
like image 726
nven Avatar asked Aug 09 '16 21:08

nven


People also ask

Can you have multiple Kwargs?

Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.

How do you pass multiple parameters to a function?

The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.

Can you pass Kwargs as a dictionary?

“ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.


2 Answers

That's a new feature introduced in Python 3.5. If you have to support Python 3.4, you're basically stuck with the update loop.

People have their own favored variations on how to combine multiple dicts into one, but the only one that's really a major improvement over the update loop is 3.5+ exclusive, so it doesn't help with this. (For reference, the new dict-merging syntax is {**kwargs1, **kwargs2, **kwargs3}.)

like image 93
user2357112 supports Monica Avatar answered Oct 21 '22 20:10

user2357112 supports Monica


One workaround mentioned in the rationale for PEP448 (which introduced that Python feature) is to use collections.ChainMap:

from collections import ChainMap

plot(**ChainMap(x_axis_params, y_axis_params, plot_params))

ChainMap was introduced in Python 3.3, so it should work in your docker instance.

like image 1
ali_m Avatar answered Oct 21 '22 18:10

ali_m