Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose and use of **kwargs? [duplicate]

What are the uses for **kwargs in Python?

I know you can do an objects.filter on a table and pass in a **kwargs argument.  

Can I also do this for specifying time deltas i.e. timedelta(hours = time1)?

How exactly does it work? Is it classes as 'unpacking'? Like a,b=1,2?

like image 760
Federer Avatar asked Nov 20 '09 09:11

Federer


People also ask

What is the purpose of Kwargs?

Kwargs allow you to pass keyword arguments to a function. They are used when you are not sure of the number of keyword arguments that will be passed in the function. Kwargs can be used for unpacking dictionary key, value pairs.

What is * Kwargs?

kwargs is variable name used for keyword arguments, another variable name can be used. The important part is that it's a dictionary and it's unpacked with the double asterisk operator ** .

When should I use Kwargs?

**kwargs are good if you don't know in advance the name of the parameters. For example the dict constructor uses them to initialize the keys of the new dictionary. It is often used if you want to pass lots of arguments to another function where you don't necessarily know the options.

How do you use args and Kwargs together?

Using *args and **kwargs in Function Calls The function will print out each of these arguments. We then create a variable that is set to an iterable (in this case, a tuple), and can pass that variable into the function with the asterisk syntax.


1 Answers

You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

>>> def print_keyword_args(**kwargs): ...     # kwargs is a dict of the keyword args passed to the function ...     for key, value in kwargs.iteritems(): ...         print "%s = %s" % (key, value) ...  >>> print_keyword_args(first_name="John", last_name="Doe") first_name = John last_name = Doe 

You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'} >>> print_keyword_args(**kwargs) first_name = Bobby last_name = Smith 

The Python Tutorial contains a good explanation of how it works, along with some nice examples.

Python 3 update

For Python 3, instead of iteritems(), use items()

like image 165
Pär Wieslander Avatar answered Oct 05 '22 07:10

Pär Wieslander