python kwargs

satya - 3/3/2024, 2:49:41 PM

Two purposes for kwargs in python

  1. Unpacking dictionaries
  2. 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")

info = {"name": "John Doe", "age": 30, "country": "USA"}

# Pass the dictionary as individual key/value pairs using **
print_info(**info)
  1. You can define a function that takes multiple key/value args: f(**kwargs)
  2. You can call such a function with multiple key value pairs explicitly
  3. Or you can define a dictionary and pass the dictionary with a (**dictionary_var) syntax
  4. Inside the function these arguments will be known as kwargs if you defined them as **kwargs
  5. The name kwargs is arbitrary