Andromeda
Note

Kwargs in Python (**kwargs)

Definition

The **kwargs syntax in Python is used in a function definition to accept an arbitrary number of keyword arguments, which are collected into a dictionary.

Why It Matters

Using **kwargs allows functions to accept optional, named arguments dynamically, which is essential for writing extensible APIs, decorators, and wrapper functions.

Core Concepts

  • Syntax: The double asterisk (**) is the actual operator that performs the key-value packing/unpacking; the name kwargs is a strong community convention.
def build_profile(first, last, **user_info):
    profile = {'first_name': first, 'last_name': last}
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
  • Data Type: Inside the function, the parameter prefixed with ** is treated as a dictionary.
  • Unpacking: The double asterisk can also be used in function calls to unpack an existing dictionary into named keyword arguments.

Connected Concepts