python kwargs
satya - 3/3/2024, 2:49:41 PM
Two purposes for kwargs in python
- Unpacking dictionaries
- Accepting arbitrary keyword arguments
satya - 3/3/2024, 2:51:10 PM
Unpacking dictionaries
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
person = {"first_name": "John", "last_name": "Doe"}
# Unpacks the person dictionary
# into the first_name and last_name arguments
greet(**person)
satya - 3/3/2024, 2:53:41 PM
A function that takes an arbitrary number of key value arguments
#Definition
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Can accept any number of keyword arguments
print_info(name="John Doe", age=30, country="USA")
satya - 3/3/2024, 2:56:07 PM
You can call the function this way too
info = {"name": "John Doe", "age": 30, "country": "USA"}
# Pass the dictionary as individual key/value pairs using **
print_info(**info)
satya - 3/3/2024, 2:58:50 PM
In summary
- You can define a function that takes multiple key/value args: f(**kwargs)
- You can call such a function with multiple key value pairs explicitly
- Or you can define a dictionary and pass the dictionary with a (**dictionary_var) syntax
- Inside the function these arguments will be known as kwargs if you defined them as **kwargs
- The name kwargs is arbitrary