Python Kwargs Example
In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has one star and delivers a variable number of non-keyworded argument lists. The function is made versatile by using these *args and **kwargs. When passing a variable's name to a function in Python, the word "kwargs" is used as the keyword argument. When handling named arguments with a function's variable-length argument dictionary, we use this kwargs.
Python kwargs Working with Examples
When unsure about the number of arguments to use in the program, we use kwargs with 2 stars (**) before the parameter name in this section. When using kwargs in Python, we indicate this with 2 stars (**). Let's examine the example below to see how kwargs are demonstrated.
Example 1:
Code:
print ("A program to display **kwargs for variable numbers of keywords:")
print("\n")
def concatenate_str (**kwargs):
x = ""
for arg in kwargs.values():
x += arg
return x
print ("The concatenated value is shown as follows:")
print (concatenate_str (a="java", b="T", c="point"))
Output:
[Running] python -u "d:\Programming\Python\test.py"
A program to display **kwargs for variable numbers of keywords:
The concatenated value is shown as follows:
javaTpoint
[Done] exited with code=0 in 0.188 seconds
As can be seen from the program above, the function was defined utilizing the arguments variable as kwargs with 2 stars before it. As a result, when we execute the function concatenate_str(), a="java," b="T," and c="point" will be iterated through using a "for" loop. Then, as seen in the output above, it prints all of these words together.
We will now see another application of **kwargs. Let's take a look at a function that was developed utilizing a name dictionary below.
Example 2:
print ("Another usage for **kwargs:")
print ("\n")
def printValue (**kwargs):
for k, v in kwargs.items():
print ("The value of {} is {}".format (k, v))
printValue (my_name="Annu", your_name="Sandeep")
Output:
Running] python -u "d:\Programming\Python\test.py"
Another usage for **kwargs:
The value of my_name is Annu
The value of your_name is Sandeep
[Done] exited with code=0 in 0.176 seconds
We can see that we used **kwargs to build a dictionary in the program mentioned above. As is common knowledge, a dictionary's output can be displayed in any order. For example, the name "Annu" may appear first, or another name such as "Sandeep". The screenshot up top makes this clear.
Since we can pass the number of arguments when using **kwargs, the output that has a dictionary built will once more present an unordered output. This demonstrates the flexibility of **kwargs when used with keyword arguments in the program. As a result, one thing to bear in mind is that the ordering of the parameters should be carefully maintained when establishing any function, and the same order can be used when calling the function; otherwise, we will encounter an error. Although using **kwargs is straightforward and helps with readability, we should use it carefully because it gives key:value pairs that must be used in the correct order.
In Python, the argument list will remain short whenever developers or consumers want numeric inputs without a fixed, known value. Here is an example of how to utilize *args and *kwargs. Let's illustrate this with several examples below.
Example 3:
The program that uses *args to supply the function's items in an iterable variable is shown below.
Code:
print ("The following program is used to demonstrate the *args:")
def function (x, y, z):
print (x, y, z)
x = [1,2,3]
function (*x)
Output:
[Running] python -u "d:\Programming\Python\test.py"
The following program is used to demonstrate the *args:
1 2 3
[Done] exited with code=0 in 0.166 seconds
The list "x" is divided into 3 separate elements in the program mentioned above that uses *args. We should also keep in mind that the aforementioned program only functions when a function's number of parameters matches the number of elements in the specified iterable variable (in this case, list "x").
We'll now examine how to use **kwargs, just like the aforementioned program does, to call a function. Let's use the example below to illustrate.
Example 4:
print ("The following program demonstrates the **kwargs used in function calls:")
def function (x, y, z):
print (x, y, z)
x = {'x': "one", 'y': "two", 'z': "three" }
function (**x)
Output:
[Running] python -u "d:\Programming\Python\test.py"
The following program demonstrates the **kwargs used in function calls:
one two three
[Done] exited with code=0 in 0.152 seconds
It is clear from the program above that we are using **kwargs, with the name variable "x" standing for list. Again, for the aforementioned program to function, it is important to keep in mind that the parameters that are supplied to the function must likewise have the same names as the keys in the dictionaries. We should also keep in mind that the number of parameters should match the number of dictionary keys.
As we saw in the section above, the list *args, which is denoted by a single star (*), is created and its contents are positional arguments that are defined by the supplied functional call. Contrarily, we saw in the aforementioned **kwargs that it produces a dictionary with keys as every element in it, the contents of which can be a keyword argument after those which are defined from the method call. As a result, the typical standards for catching positional and keyword arguments are *args and **kwargs, respectively. The use of those two types of argument in a single function precludes placing or writing **kwargs before *args, which will result in an error.
Conclusion
In this article, we come to the conclusion that when calling a function with parameters, **kwargs is a keyword argument length list. We saw straightforward examples of **kwargs in this. We also saw the use of **kwargs, which can be used when deciding how many parameters to utilize.
Next, we learned the distinction between *args and **kwargs as well as how to utilize each in a function call. This article also included several crucial reminders, such as the requirement to call a function with the same amounts of arguments and components. Additionally, we saw that when **kwargs is run, a dictionary that presents an unordered element is created.