Motivation: To introduce kwargs in functions and understand
‘kwargs’ in python functions is used to accept any number of key word arguments and so the word ‘kwargs’ meaning keyword arguments.
When we define the function we use **kwargs as an argument.It takes the keywords as a dictionary, where the keys are the argument names and the values are the argument values.
Example:
def kwargs_example(a, b, **kwargs):
print(a)
print(b)
print(len(kwargs))
print(type(kwargs))
for key, value in kwargs.items():
print(key, value)
kwargs_example(10, 20, name='Tony', place='NYC')
Output:
10
20
2
<class 'dict'>
name Tony
place NYC
Process finished with exit code 0
Use: It is useful when we want to create functions that can accept any number of keyword args without explicitly defining them in the function.
I hope you can use kwargs in your code and try out the flexibility. Thank you!