This question already has an answer here:
So I have difficulty with the concept of *args
and **kwargs
.
So far I have learned that:
*args
= list of arguments - as positional arguments**kwargs
= dictionary - whose keys become separate keyword arguments and the values become values of these arguments.
I don't understand what programming task this would be helpful for.
Maybe:
I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument?
Is there a simple example to explain how *args
and **kwargs
are used?
Also the tutorial I found used just the "*" and a variable name.
Are *args
and **kwargs
just placeholders or do you use exactly *args
and **kwargs
in the code?
You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs (courtesy of archive.org) (the original, dead link is here).
In a nutshell, both are used when optional parameters to a function or method are used. As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in:
These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.
But since these parameters hide the actual parameter names, it is better to avoid them.
Here's one of my favorite places to use the
**
syntax as in Dave Webb's final example:I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!
Here's an example that uses 3 different types of parameters.
*args and **kwargs are special-magic features of Python. Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function:
and use it like: sumFunction(3,4,6,3,6,8,9).
**kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary.
Calling someFunction(text="foo") will print foo.