What is ‘kwargs’ in python?

Santosh J
Jul 11, 2023

--

Motivation: To introduce kwargs in functions and understand

credit: https://cdn.pixabay.com/photo/2016/11/29/02/53/python-1866944_1280.jpg

‘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!

--

--

Santosh J

Problem solver, with experience in Product Management, Data Science, Strategy & Analytics, Cloud Engineering. I enjoy movies, food and reading.