Master Python kwargs get With This Article

In this article, we will be discussing kwargs and kwargs get in Python. In Python, keyword arguments(kwargs) are values that are accessed by specific parameters in a function. A keyword argument is followed by a parameter and the assignment operator (=). In Python, keyword arguments can be passed through dictionaries.

Let’s look at the different ways keyword / non-keyword arguments can be passed to a function.

What is Python Kwargs Get?

To retrieve a value that’s not present within the dictionary, we can use the kwargs get method. Kwargs get allows us to set default values to a function. Let’s look at the following program.

def myFunction(self, **kwargs):
     self.value2 = kwargs.get('value2',"value 2 contents")

This is similar to :

def myFunction(self, value2="value 2 contents", **kwargs):
     ...
     ...

In Python, the number of arguments to pass is defined during function creation. If additional arguments are passed with the function call, it will result in a TypeError.

If the number of non-keyword arguments to pass is uncertain, we can use *args as an argument. The *args argument is denoted using a single asterisk. Let’s look at the following example to understand better. Practice the following examples using our online compiler.

Passing n Parameters to a Function Using Python *args

def addition(*value):
 sum = 1
 for i in value:
    sum = sum + i
 print("total sum:", sum)

addition(5,5)
addition(1,0,8)
addition(28,7,2022)

Output

total sum: 11
total sum: 10
total sum: 2058

If the number of keyword arguments to pass is uncertain, we can use **kwargs as an argument. In **kwargs, the arguments are passed in a dictionary. The name of the dictionary is the same as the parameter without double asterisks.

Obtaining Dictionary Values Using Python kwargs

def employee(**details):
  print("Data type of argument:",type(details))

  for key, value in details.items():

    print("{} : {}".format(key, value))
 

 
employee(fName = "Joe", lName = "Rogan", role="Junior Dev.", salary="30000")
employee(fName= "Steve", lname = "Wozniack", role="Manager", salary ="100000", location="San Fransisco")
employee(fName = "Mark", lName = "Twain", role="Recruit")   

 

Output

Data type of argument: <class 'dict'>
fName : Joe
lName : Rogan
role : Junior Dev.
salary : 30000

Data type of argument: <class 'dict'>
fName : Steve
lname : Wozniack
role : Manager
salary : 100000
location : San Fransisco

Data type of argument: <class 'dict'>
fName : Mark
lName : Twain
role : Recruit

The employee() function is defined with **details as a parameter. This allows us to pass arguments in the form of dictionaries of different lengths. All 3 of the function calls have argument length.

How To Return All Keys In Python Kwargs

We know kwargs is a dictionary. This means we can access the items how we would in a standard Python dictionary. With the help of the .keys() function, we can achieve this. Let’s refer to the following example.

def employee(**details):

  print(details.keys())
    
    
employee(fName = "Joe", lName = "Rogan", role="Junior Dev.", salary="30000")
employee(fName= "Steve", lname = "Wozniack", role="Manager", salary ="100000", location="San Fransisco")
employee(fName = "Mark", lName = "Twain", role="Recruit")   

Output

dict_keys(['fName', 'lName', 'role', 'salary'])
dict_keys(['fName', 'lname', 'role', 'salary', 'location'])
dict_keys(['fName', 'lName', 'role'])

Kwargs Get vs. Kwargs Pop

Kwargs GetKwargs Pop
kwargs get returns the value of the dictionary ket. The key returns the default value if it is not in the dictionary.kwargs pop removes and returns the value of the dictionary key. The key returns the default value if it is not in the dictionary.
If the default value is not mentioned, None is returned to prevent KeyError.If the default value is not mentioned, None is returned to prevent KeyError.
After passing a key to Kwargs get, the key or value can still be accessedAfter passing a key to Kwargs pop, the key or value can no longer be accessed

How To Capture URL Parameters Using Kwargs Request Get in Python Django

Let’s see how we can retrieve the parameters of a URL using request.GET.get()

Let wp/search/?post=pythonpool be our sample URL and post as our parameter.

Our function call in order to fetch post would be :

request.GET.get('post', ' ')

This retrieves 'post' if present or returns the default value of ' '.

A complete function would be:

def PythonPoolPost(request, admin=None):
      adminstrator = User.objects.get(admin=admin)
      post = requests.GET.get('post)

How To Call Kwargs From Command Line

In order to call keyword arguments from the command line, you can do so by creating the following primary function.

import sys

def main(foo, bar, *args):
    print ("Function Call to 'main'")

    print ("foo = %s" % foo)
    print ("bar = %s" % bar)

    for eachArg in args:
        key = eachArg.split("=")[0]
        value = eachArg.split("=")[1]

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Insufficient Arugments")
    if len(sys.argv) != 3:
        main(sys.argv[1], sys.argv[2], *sys.argv[3:])
    else:
        main(sys.argv[1], sys.argv[2])

The main function has a conditional statement that decides the number of arguments to fetch based on the total number.

If the number of arguments is less than three, the function proceeds not to fetch the arguments.

If the number of arguments is any number above three, it proceeds to collect n number of arguments.

Finally, the else block is executed if there are no keyword arguments in the function.

Sample/Output

Function Call to 'main'
foo = a
bar = b
...
...
...
!>python sample.py foo bar key=value
Function Call to 'main'
foo = foo 
bar = bar
Keyword argument: key = value

How to Pass a List of Kwargs in Python

It may not be possible to pass a list. However, values can be passed through a dictionary.

def myFunction(**kwargs):
     print(kwargs)

keyWords = {'keyword1': 'Python', 'keyword2': 'Pool'}
myFunction(keyword1='Python', keyword2='Pool')

Output

{'keyword2': 'Python', 'keyword1': 'Pool'}
{'keyword2': 'Python', 'keyword1': 'Pool'}

As you can see, both yield similar outputs.

How To Unpack Kwargs in Python

Functions that have keyword arguments can accept a dictionary as a single parameter. The dictionary should contain the keywords present in the function.

def myFunction(product, price, qty):
     print("Customer Ordered: ", qty , product, "for", price)

valueDict = {'product': "iPhone 13", 'price': 90000, 'qty': 1}

myFunction(**valueDict)

Output

Customer Ordered:  1 iPhone 13 for 90000

FAQs on Python kwargs get

What is super () _ Init_ * * Kwargs?

The super() function in Python is used to give access to methods of a child class. Calling super ()._ Init_(**kwargs) will expand the values into keyword arguments.

How do I unpack Kwargs?

Using the keywords in the function, you can pass values through a dictionary. Note that the dictionary must contain the keywords present in the function.

Why do we use * in Python?

In numerical operations, the * is used as a multiplication operator.
However, the * can be used in function declaration and allows n number of arguments to be passed. The multiple arguments are passed as a tuple.

Conclusion

In this article, we’ve looked at how a function can take n arguments using *args and **kwargs. Python args allows you to pass n non-keyword arguments, whereas Python kwargs allows you to pass n keyword arguments. Python kwargs pass their values through a dictionary.

Each argument has a key and value in Python kwargs. Python kwargs get you to fetch values that are not present in the dictionary of arguments. We have discussed how we can set default arguments to a function using kwargs get. We’ve established the differences between kwargs get and kwargs pop.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments