How to use `**kwargs` in Python
Published on Aug. 22, 2023, 12:15 p.m.
To use **kwargs
in Python, you can define a function using the **
syntax in the function definition. Here’s an example:
def my_function(**kwargs):
for key, value in kwargs.items():
print(f'{key}: {value}')
my_function(param1='value1', param2='value2')
This defines a function my_function
with a **kwargs
parameter that allows it to accept an arbitrary number of keyword arguments. The function then loops through the kwargs
dictionary and prints the key-value pairs.
When calling the function, you can pass any number of keyword arguments:
my_function(param1='value1', param2='value2')
This will output:
param1: value1
param2: value2
You can also use the **
syntax to unpack a dictionary into keyword arguments when calling a function:
my_dict = {'param1': 'value1', 'param2': 'value2'}
my_function(**my_dict)
This will output:
param1: value1
param2: value2
**kwargs
can be used in a class definition
**kwargs
can be used in a class definition just like in any other function definition. Here’s an example:
class Example:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
example = Example(param1="value1", param2="value2")
print(example.param1) # "value1"
print(example.param2) # "value2"
In this example, we define a class Example
that has an __init__
method that accepts any number of keyword arguments using the **kwargs
syntax. Inside the __init__
method, we update the instance’s __dict__
with the keyword arguments passed in, so that they are stored as instance variables.
You can then create an instance of the class and pass in any number of keyword arguments:
example = Example(param1="value1", param2="value2")
And you can access the instance variables like this:
print(example.param1) # "value1"
print(example.param2) # "value2"