*args & **kwargs in python
..demistyfied & how to use them
How many times have we come across *args and **kwargs mentioned in the python functions help documents. Have you wondered what these mean and how is it used?
Well, here are the answers !
*args
*args
` refers to arguments or the parameters we pass to a function so that it can work on these arguments and what it is supposed to do. For the sake of an example, lets create a user-defined function that takes in 2 arguments and returns the sum.
Here we have not explicitly passed the names of the arguments x
and y
. python assumes that the first argument refers to x
and the second to y
and this method is also referred to as passing positional arguments. But what if we want to create a function to add 3 numbers? Or 4 numbers? The above function does not work for more than 2 numeric arguments:
We would not like to keep creating new functions just to add this capability right? We would want a function that can be flexible to take in any number of arguments and perform the same task as the one above.
Here is where the *args
technique comes in handy. Let's create a new function that performs the same task, but can take an unspecified number of arguments.
Using the *args technique we can unpack the arguments passed into the function as a list inside the function and do what we need to do with it inside the function.
**kwargs
kwargs refers to key word arguments. This technique is when we explicitly pass the argument names, like so:
The above is a very simple function for created for the sake of demonstration. But imagine a function that takes in a ton of arguments. Then the function call can become very long and result in a cluttered line of code. **kwargs
technique comes in very handy in such situations.
We can create a dictionary of the argument names and the value we want to pass as key-value pairs in the dictionary and just pass the dictionary to the function prefixed by **. The dictionary elements are unpacked inside the function and the respective argument values processed.
The result is a more elegant function call and also more readable code. Hope you found this interesting. If you like this article you may also want to check out my other articles. Would love to connect with you on bala@python4u.in