Tuesday, 3 May 2022

Python *args and **kwargs

 https://www.analyticsvidhya.com/blog/2021/07/python-args-and-kwargs-in-2-minutes/#:~:text=**kwargs%20stands%20for%20keyword,the%20form%20of%20a%20dictionary.

https://stackoverflow.com/questions/1769403/what-is-the-purpose-and-use-of-kwargs




What is *args doing?

*args allows you to pass the desired number of arguments to the function. Args generally means arguments in this case. Let’s see an example.

def demo(*args):
    print(args)

Call the function

demo("Humpty", "Dumpty") # call with two arguments

Output:

('Humpty', 'Dumpty')



You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print "%s = %s" % (key, value)
... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith



No comments:

Post a Comment