patternpythonCriticalCanonical
What is the purpose and use of **kwargs?
Viewed 0 times
andusethekwargspurposewhat
Problem
What are the uses for
I know you can do an
Can I also do this for specifying time deltas i.e.
How exactly does it work? Is it classified as 'unpacking'? Like
**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 classified as 'unpacking'? Like
a,b=1,2?Solution
You can use
You can also use the
The Python Tutorial contains a good explanation of how it works, along with some nice examples.
Python 3 update
For Python 3, instead of
**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 = DoeYou 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 = SmithThe 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()Code Snippets
>>> 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>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = SmithContext
Stack Overflow Q#1769403, score: 971
Revisions (0)
No revisions yet.