Introduction to Python kwargs
In this article, we discuss kwargs concept in Python. In Python, args is a variable that has one star which passes a variable number of non-keyworded argument list whereas kwargs have two stars which pass a variable number of the keyworded argument list to the function. These both *args and **kwargs are used for making the function flexible. In Python, we use kwargs that are keyword argument is used to when you provide a name to a variable as we pass it to the function. This kwargs is used when we want to handle named arguments with a variable-length argument dictionary to a function.
Working of kwargs in Python with examples
In this section, when we are not sure of how many arguments are needed to use in the program then we use kwargs with two stars (**) before the parameter name. In Python, when we are using kwargs we declare it with two stars (**). Now let us see the demonstration of kwargs in the below example.
Example #1
Code:
print("Program to demonstrate **kwargs for variable number of keywords:")
print("\n")
def concatenate(**kwargs):
r = ""
for arg in kwargs.values():
r += arg
return r
print("The concatenated value is displayed as follows:")
print(concatenate(a="Educba", b="Training", c="Institue"))
Output:
In the above program, we can see that we have defined function using the argument variable as kwargs with two stars before it. So when we call this function concatenate() which will iterate through the given kwargs dictionary a=”Educba”, b=”Training”, c=”Institue” using “for” loop. Then it prints all these words together as shown in the output and screenshot above.
Now we will see another use of **kwargs. Let us see below a function that is created using a dictionary of names.
Example #2
Code:
print("Another use of **kwargs:")
print("\n")
def print_values(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
print_values(my_name="Rahul", your_name="Ratan")
Output:
In the above program, we can see we have created a dictionary using **kwargs. As we known dictionary can be unordered the output might display the names first “Rahul” or with another name “Ratan” so the dictionary has no order to display the output. This can be seen in the above screenshot.
Therefore when we use **kwargs we can pass any number of arguments and these can also have the output which has a dictionary created will display an unordered output again. By this, we can say that **kwargs are flexible to use with keyword arguments in the program. Therefore one thing we should remember is that we should properly keep the order of the parameters when creating any function and we can use the same order in the function call else if we do not follow the order then we will get an error. The use of **kwargs is very simple and to provide readability but we should use it with care as it provides the key: value pairs as to follow the order.
In Python, whenever the developers or users need number inputs without fix known value within the argument list will remain small. Let us see below how *args and *kwargs are used. Let us demonstrate below with examples.
Example #3
Below is the program that uses *args to pass the elements to the function in an iterable variable.
Code:
print("Program to demonstrate the *args is as follows:")
def func(a, b, c):
print(a, b, c)
a = [1,2,3]
func(*a)
Output:
In this above program, uses *args where the list “a” is broken into 3 different elements. we should also note that the above program works only when the number of parameters of a function is the same as the number of elements in the given iterable variable (here it is list “a”).
Now we will see, about **kwargs, to call the function as the above program with *args. Let us demonstrate using the below example.
Example #4
Code:
print("Program to demonstrate the **kwargs used in function call is as follows:")
def func(a, b, c):
print(a, b, c)
a = {'a': "one", 'b': "two", 'c': "three" }
func(**a)
Output:
In the above program, we can see we are using **kwargs with the name variable as “a” which is list. Again the above program to work we need to note that the name of the parameters that are passed to the function must also have the same name in the dictionary where these act as the keys in the dictionary. And we should also note that the number of arguments should also be the same as the number of keys in the dictionary.
In the above section, we saw that *args which has a single star (*) which creates the list whose contents of the list are positional arguments that are defined from the given functional call. Whereas we saw in the above **kwargs which has a double star (**) which creates a dictionary with keys as each element in it whose contents can be keyword argument after those that are defined from the function call. Hence *args and **kwargs are standard conventions to catch positional and keyword arguments respectively. We should also note that when we are using these two types of arguments in one function then we cannot place or write **kwargs before *args, else we will receive an error.
Conclusion
In this article, we conclude that **kwargs is a keyword argument length-list when creating the function with parameters. In this, we saw simple examples of **kwargs. We also saw the use of **kwargs when we are not sure of how many parameters to use we can use kwargs. Then we also saw that *args and **kwargs difference and how they are used when used in the function call. In this article, we also saw some important notes to remember such as we need to pass the same number of arguments with the same number of elements when calling the function. We also saw **kwargs creates a dictionary that displays an unordered element when executed.
Recommended Articles
This is a guide to Python kwargs. Here we discuss the introduction, working of Python kwargs, and respective examples with code implementation. You may also have a look at the following articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses