I have a function
def wrapper_function(url, **kwargs)
def foo():
if kwargs:
return do_something(url, kwargs)
else:
return do_something(url)
The do_something()
function can either have one or more parameters.
When I call the wrapper_function()
, want to call it either like
wrapper_function('www.bar.com')
or
wrapper_function('www.bar.com', selected_clients=clients)
so that do_something('www.bar.com', selected_clients=clients)
.
However, when I approach it like this, I get an error
clients is not defined
.
How can I pass on the params exactly like they are with the keyword into an inner function? Important, that keyword needs to be variable as well.
**kwargs: Pass multiple arguments to a function in Python If so, use **kwargs . **kwargs allow you to pass multiple arguments to a function using a dictionary. In the example below, passing **{'a':1, 'b':2} to the function is similar to passing a=1, b=1 to the function.
*args collects the positional arguments that are not explicitly defined and store them in a tuple. **kwargs does the same as *args but for keyword arguments. They are stored in a dictionary because keyword arguments are stored as name-value pairs.
Summary. Use the Python **kwargs parameter to allow the function to accept a variable number of keyword arguments. Inside the function, the kwargs argument is a dictionary that contains all keyword arguments as its name-value pairs. Precede double stars ( ** ) to a dictionary argument to pass it to **kwargs parameter.
“ 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.
When your function takes in kwargs in the form foo(**kwargs)
, you access the keyworded arguments as you would a python dict. Similarly, to pass the dict to a function in the form of several keyworded arguments, simply pass it as **kwargs
again. So, in your case,
do_something(url, **kwargs)
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