Skip to content

What is the purpose and use of **kwargs?

In Python, **kwargs is a way to pass a keyworded, variable-length argument list. The name kwargs is a convention (you can use any valid identifier), but it stands for "keyword arguments". It allows you to pass a variable number of keyword arguments to a function. The double asterisk (**) before the parameter name indicates that it will collect these arguments into a dictionary.

Here is an example of a function that uses **kwargs:

An example of a function that uses kwargs in Python

python
def print_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(key, ":", value)

print_kwargs(name="John", age=30, city="New York")

In this example, the function print_kwargs() accepts a keyworded, variable-length argument list, which is represented by the parameter **kwargs. Inside the function, the keyword arguments are accessed as a dictionary using the kwargs parameter.

The above code would output:

console
name : John
age : 30
city : New York

Note that **kwargs must always be placed after positional arguments and *args in a function definition. You can use it to pass keyword arguments to a function, which can then use them to set default values or perform the desired operations.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.