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
?
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.
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 ** .
**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.
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.
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.
For Python 3, instead of iteritems()
, use items()
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