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)
Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.
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.
“ 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.
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}
.)
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.
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