Python kwargs get: A Comprehensive Guide

In Python programming, a function can be used as reusable code that performs similar operations. But a function cannot take variable numbers of arguments because if you pass a variable number of arguments, it will throw TypeError.

If you define a function with three arguments and at the time of call, if you pass five arguments, then it will throw the TypeError.

To resolve the TypeError issue, we can either use *args or **kwargs. Let’s understand both in detail.

What is *args in Python

Python *args is a syntax that passes an arbitrary number of arguments to a function. The *args syntax allows you to pass a variable number of arguments to a function, and it is often used in conjunction with the **kwargs syntax to capture all of the arguments passed to a function.

Let’s understand it by an example.

Implementation of *args in Python program

To pass a variable number of arguments to a function in Python, use the *args (Non-Keyword Arguments). Python has *args, allowing us to pass a variable number of non-keyword arguments to a function.

def user_defined_function(*args):
  print(type(args))

  # Print the number of arguments passed to the function
  print(len(args))

  # Print the arguments passed to the function
  print(args)


# Call the function with two arguments
user_defined_function(11, 21)

# Call the function with four arguments
user_defined_function(11, 21, 19, 46)

Output

<class 'tuple'>
2
(11, 21)
<class 'tuple'>
4
(11, 21, 19, 46)

In this example, we created a function called user_defined_function() that takes an arbitrary number of arguments using the *args syntax. Inside the function, we use the type() function to print the type of the args variable and the len() function to print the length of arguments passed.

Let’s take another example. We use the *args as an argument when we are uncertain about the total number of arguments to pass in the function.

def multiplier(*num):
 multi = 1
 for i in num:
    multi = multi * i

 print("multiplier:", multi)


multiplier(1, 2)
multiplier(1, 2, 3, 4)
multiplier(1, 2, 3, 4, 5)

Output

multiplier: 2
multiplier: 24
multiplier: 120

In this example, we pass *num as an argument representing variable-length arguments. For instance, we call the multiplier function the first time with two arguments, the second time with four arguments, and the third time with five arguments.

Inside the multiplier(*num) function, we used for loop, which multiplies the passed argument and prints the result.

What is **kwargs in Python?

Python kwargs is a dictionary containing keyword arguments passed to a function. The kwargs dictionary allows you to pass an arbitrary number of keyword arguments to a function, and it is often used in conjunction with the *args syntax to capture all of the arguments passed to a function.

To pass a variable-length keyword argument to a function in Python, use the **kwargs. We denote kwargs with a double asterisk ** before the parameter name.

The arguments are passed as a dictionary, and these arguments make a dictionary inside a function with a name same as the parameter, excluding the double asterisk **.

def spider_man(**arguments):
 print("\nData type of argument:",type(data))

 for key, value in data.items():
 print("{} is {}".format(key, value))

spider_man(Firstname="Peter", Lastname="Parker", Age=22, Phone=1234567890)
spider_man(Firstname="Peter 2", Lastname="Parker", Email="peter@nomail.com", Country="USA", Age=45, Phone=9876543210)
spider_man(Firstname="Peter 3", Lastname="Parker", Email="parker@nomail.com", Country="USA")

Output

Data type of argument: <class 'dict'>
Firstname is Peter
Lastname is Parker
Age is 22
Phone is 1234567890

Data type of argument: <class 'dict'>
Firstname is Peter 2
Lastname is Parker
Email is peter@nomail.com
Country is USA
Age is 45
Phone is 9876543210

Data type of argument: <class 'dict'>
Firstname is Peter 3
Lastname is Parker
Email is parker@nomail.com
Country is USA

In the above code, we have a function spider_man() with **arguments as a parameter. We passed two dictionaries with variable argument lengths to the spider_man() function. Then, we used for loop inside the spider_man() function, which works on the data of the given dictionary and prints the value of the dictionary.

To format the output in Python, we can use the str.format() method. The *args and **kwargs make the function more adjustable and flexible. The **kwargs has all the methods other dictionaries can have.

In this example, you can say that **kwargs will create a dictionary, which is why it has a key and value. To get the value based on the key, you can use the get() method. 

Python kwargs get

To access the values in the kwargs dictionary in Python, use the get() method. The get() method takes a key as its argument and returns the value associated with that key in the dictionary. If the key is not found in the dictionary, the get() method will return None.

self.value = kwargs.get('value',"default value")

You can write the following if you use a specific argument with a particular default value.

value = dict.get(key, default_when_key_is_missing)

We generally use the following code to get the value associated with a specific key in the Python dictionary.

value = dict[key]

But trying to get a value for a key that doesn’t exist will throw an exception.

Fortunately, there is a **kwargs get() method, which we can use, which is very convenient in this case.

If we prefer to assign the class attribute more traditionally, self.value = kwargs[‘value’], we must confirm that the key age and a default value exist in kwargs before asking for it.

To add the needed keys to kwargs and set their default values, we can use the following code:

kwargs.setdefault('age', 'x')

Implementation of kwargs.get() method in Python

def user_defined_function(*args, **kwargs):
  # Get the value associated with the 'name' key in the kwargs dictionary
  name = kwargs.get('name')

  # Print the value of the 'name' key
  print(name)


# Call the function with a keyword argument
user_defined_function(name='KRUNAL') # 'KRUNAL'

# Call the function without the keyword argument
user_defined_function() # None

In this example, we define a function called user_defined_function() that takes an arbitrary number of arguments and keyword arguments.

Inside the function, we use the get() method of the kwargs dictionary to get the value associated with the name key. If the name key is not found in the kwargs dictionary, the get() method will return None.

Conclusion

The get() method of kwargs takes a key as its argument and returns the value associated with that key in the dictionary. If the key is not found in the dictionary, the get() method will return None.

That’s it.

Leave a Comment