Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass **kwargs through to inner function [duplicate]

Tags:

python

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.

like image 395
Andrew Graham-Yooll Avatar asked Jun 08 '17 13:06

Andrew Graham-Yooll


People also ask

How do you pass multiple Kwargs Python?

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

What datatype are the * Kwargs stored when passed into a 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.

How do you pass Kwargs to a function?

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.

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.


1 Answers

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)
like image 76
codelessbugging Avatar answered Sep 24 '22 01:09

codelessbugging