Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:
def my_sum(*args):
return sum(args)
It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.
You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.
There's a more in-depth look in the official Python documentation on arbitrary argument lists.
Answer from Paul D. Waite on Stack OverflowWhat are *args and **kwargs ?
python - What do *args and **kwargs mean? - Stack Overflow
What is the use of **kwargs?
python - What is the purpose and use of **kwargs? - Stack Overflow
Videos
I read few explaination but I just understood they are for variable arguments other than this I am confused
Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:
def my_sum(*args):
return sum(args)
It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.
You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.
There's a more in-depth look in the official Python documentation on arbitrary argument lists.
Also, we use them for managing inheritance.
class Super( object ):
def __init__( self, this, that ):
self.this = this
self.that = that
class Sub( Super ):
def __init__( self, myStuff, *args, **kw ):
super( Sub, self ).__init__( *args, **kw )
self.myStuff= myStuff
x= Super( 2.7, 3.1 )
y= Sub( "green", 7, 6 )
This way Sub doesn't really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.
I understand the use of *args, you don't know how many variables will be passed so you store them as a list and later use them. But why would you use **kwargs at all?
From what I understand, correct me if I'm wrong, **kwargs are undeclared variables in a function that get passed as keywords and work like a dictionary. Something like this:
def function(**kwargs):
print(kwargs)
function(arg1="Cat", arg2="Dog", arg3="Parrot")
############## Result
{arg1: "Cat", arg2: "Dog", arg3: "Parrot"}Why would you do this when you can just declare the variables as parameters like this:
def function(arg1, arg2, arg3):
print(arg1, arg2, arg3)
function("Cat", "Dog", "Parrot")
######## Result
"Cat Dog Parrot"Why would you do it the first way instead of the second way if the results are basically the same? I understand the theory behind it but I just don't see any practical use for it. I'd like some examples of real life cases where you would need **kwargs.
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()
Unpacking dictionaries
** unpacks dictionaries.
This
func(a=1, b=2, c=3)
is the same as
args = {'a': 1, 'b': 2, 'c':3}
func(**args)
It's useful if you have to construct parameters:
args = {'name': person.name}
if hasattr(person, "address"):
args["address"] = person.address
func(**args) # either expanded to func(name=person.name) or
# func(name=person.name, address=person.address)
Packing parameters of a function
- Use
.items()instead of.iteritems()for python 3
def setstyle(**styles):
for key, value in styles.iteritems(): # styles is a regular dictionary
setattr(someobject, key, value)
This lets you use the function like this:
setstyle(color="red", bold=False)
Notes
kwargsis 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**.- Other iterables are unpacked with the single asterisk operator
* - To prevent confusion, it's probably best to stick with the recognized variable names,
kwargsandargs, for dictionaries and other iterables respectively.
Resources
- PEP 448: Additional Unpacking Generalizations
- Real Python: Python args and kwargs: Demystified
- What do * and ** before a variable name mean in a function signature?
You can pass a default value to get() for keys that are not in the dictionary:
self.val2 = kwargs.get('val2',"default value")
However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place?
def __init__(self, val2="default value", **kwargs):
While most answers are saying that, e.g.,
def f(**kwargs):
foo = kwargs.pop('foo')
bar = kwargs.pop('bar')
...etc...
is "the same as"
def f(foo=None, bar=None, **kwargs):
...etc...
this is not true. In the latter case, f can be called as f(23, 42), while the former case accepts named arguments only -- no positional calls. Often you want to allow the caller maximum flexibility and therefore the second form, as most answers assert, is preferable: but that is not always the case. When you accept many optional parameters of which typically only a few are passed, it may be an excellent idea (avoiding accidents and unreadable code at your call sites!) to force the use of named arguments -- threading.Thread is an example. The first form is how you implement that in Python 2.
The idiom is so important that in Python 3 it now has special supporting syntax: every argument after a single * in the def signature is keyword-only, that is, cannot be passed as a positional argument, but only as a named one. So in Python 3 you could code the above as:
def f(*, foo=None, bar=None, **kwargs):
...etc...
Indeed, in Python 3 you can even have keyword-only arguments that aren't optional (ones without a default value).
However, Python 2 still has long years of productive life ahead, so it's better to not forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3!