Overview: **kwargs in Python [**kwargs = Variable-Length Keyword Arguments]
A function can define parameters for the keyword arguments it expects. However, some functions need to accept different keyword arguments in different function calls.
The Need for Variable-Length Keyword Arguments
Consider a function that displays information about a person. One call may include a name and age, while another may also include a city or job. Defining a separate parameter for every possible detail can make the function less flexible.
Python provides **kwargs for situations like this. It allows a function to accept a variable number of keyword arguments and makes the collected arguments available inside the function as a dictionary.
What Is **kwargs in Python?
**kwargs is a special parameter syntax used in a Python function definition to collect a variable number of keyword arguments.
When the function is called, Python collects the keyword arguments handled by **kwargs into a dictionary. The keyword names become dictionary keys, and their corresponding values become dictionary values.
The name kwargs is a conventional name that stands for keyword arguments. Python does not require this exact name. The two asterisks (**) tell Python to collect the keyword arguments.
What **kwargs Provides
A function with **kwargs does not need to define every possible keyword argument as a separate parameter. This allows different function calls to provide different keyword arguments.
For example, one call can provide only a name, while another can provide a name, age, and city. The function can receive all of them through **kwargs.
Example: Basic **kwargs
def show_details(**kwargs):
print(kwargs)
show_details(name="Alice", age=25)
# Output:
{'name': 'Alice', 'age': 25}
Explanation: Here, name="Alice" and age=25 are keyword arguments. Python collects them into the kwargs dictionary. The keywords become keys, and their values become the corresponding dictionary values.
Note: This tutorial covers how **kwargs works, how to pass and access collected keyword arguments, how to iterate over them, how to combine **kwargs with regular parameters and *args, how to unpack dictionaries with **, and common mistakes to avoid.
How **kwargs in Python Works
When a function contains **kwargs, Python collects the keyword arguments that are not assigned to other parameters and makes them available inside the function as a dictionary.
Keyword Arguments Collected by **kwargs
Keyword arguments are passed using the name=value form.
When these arguments are collected by **kwargs, their names become dictionary keys and their values become dictionary values.
Example: Collecting Keyword Arguments
def show_details(**kwargs):
print(kwargs)
show_details(name="Alice", age=25, city="Delhi")
# Output:
{'name': 'Alice', 'age': 25, 'city': 'Delhi'}
Explanation: Python collects the three keyword arguments into the kwargs dictionary. The keys are "name", "age", and "city", while their corresponding values are "Alice", 25, and "Delhi".
Passing Keyword Arguments to **kwargs
A function with **kwargs can receive one or more keyword arguments in a function call. Different calls can also provide different sets of keyword arguments.
The following examples show the main ways to pass keyword arguments to **kwargs.
- Passing a Single Keyword Argument
- Passing Multiple Keyword Arguments
- Passing Different Keyword Arguments
1. Passing a Single Keyword Argument
You can pass one keyword argument using the name=value form.
Example
def show_details(**kwargs):
print(kwargs)
show_details(name="Alice")
# Output:
{'name': 'Alice'}
Explanation: Here, name="Alice" is the only keyword argument. Python collects it in the kwargs dictionary.
2. Passing Multiple Keyword Arguments
You can pass multiple keyword arguments in the same function call. Separate the arguments with commas.
Example
def show_details(**kwargs):
print(kwargs)
show_details(name="Alice", age=25, city="Delhi")
# Output:
{'name': 'Alice', 'age': 25, 'city': 'Delhi'}
Explanation: The function receives three keyword arguments, which Python stores as key-value pairs in kwargs.
3. Passing Different Keyword Arguments
A function with **kwargs does not require the same keyword arguments in every call. Each call can provide a different set of keywords.
Example
def show_details(**kwargs):
print(kwargs)
show_details(name="Alice")
show_details(name="Bob", age=30)
show_details(city="Delhi", country="India")
# Output:
{'name': 'Alice'}
{'name': 'Bob', 'age': 30}
{'city': 'Delhi', 'country': 'India'}
Explanation: Each call provides a different set of keyword arguments. Because the function uses **kwargs, it can collect each set without defining separate parameters for every possible keyword.
Accessing Values in **kwargs
Because **kwargs is a dictionary, you can use standard dictionary operations to access its values.
The following examples show three common ways to access or check values in kwargs.
1. Accessing a Value by Key
Use a key inside square brackets to access its corresponding value in kwargs.
Example
def show_details(**kwargs):
print(kwargs["name"])
show_details(name="Alice", age=25)
# Output:
Alice
Explanation: kwargs["name"] accesses the value stored under the "name" key.
2. Checking Whether a Key Exists
Use the in operator to check whether a key exists before accessing its value.
Example
def show_details(**kwargs):
if "age" in kwargs:
print("Age:", kwargs["age"])
show_details(name="Alice", age=25)
# Output:
Age: 25
Explanation: The expression "age" in kwargs checks whether the "age" key exists. Python accesses the value only when the key is present.
3. Using kwargs.get()
The get() method lets you access a value by key without raising an error when the key is missing. If the key does not exist, it returns None by default.
Example
def show_details(**kwargs):
age = kwargs.get("age")
print("Age:", age)
show_details(name="Alice")
# Output:
Age: None
Explanation: The kwargs.get("age") expression looks for the "age" key. Because the key is not present, get() returns None.
You can also provide a default value for a missing key.
def show_details(**kwargs):
age = kwargs.get("age", 18)
print("Age:", age)
show_details(name="Alice")
# Output:
Age: 18
Explanation: Here, 18 is returned because the "age" key is not present in kwargs.
Iterating Over **kwargs in Python
Python stores the keyword arguments collected by **kwargs in a dictionary. A for loop can be used to go through its keys, values, or key-value pairs.
The following examples show the three common ways to iterate over kwargs.
1. Iterating Over Keys
A for loop goes through the keys of kwargs by default.
Example
def show_details(**kwargs):
for key in kwargs:
print(key)
show_details(name="Alice", age=25, city="Delhi")
# Output:
name
age
city
Explanation: The loop assigns each dictionary key to key one at a time.
2. Iterating Over Values
Use the values() method to loop through the values stored in kwargs.
Example
def show_details(**kwargs):
for value in kwargs.values():
print(value)
show_details(name="Alice", age=25, city="Delhi")
# Output:
Alice
25
Delhi
Explanation: The kwargs.values() method provides the dictionary values, and the loop assigns each value to value.
3. Iterating Over Keys and Values
Use the items() method when both the key and its corresponding value are needed in the same loop.
Example
def show_details(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
show_details(name="Alice", age=25, city="Delhi")
# Output:
name : Alice
age : 25
city : Delhi
Explanation: The kwargs.items() method provides each key-value pair. The loop assigns the key to key and its corresponding value to value.
Using **kwargs With Regular Parameters
A function can use regular parameters and **kwargs in Python together. Regular parameters handle values the function expects, while **kwargs collects additional keyword arguments.
The following examples show how required parameters and multiple regular parameters can be combined with **kwargs.
- Required Parameters With
**kwargs - Parameter Order With
**kwargs - Multiple Regular Parameters and
**kwargsTogether
1. Required Parameters With **kwargs
A required parameter can be defined before **kwargs. The required parameter receives its value directly, while additional keyword arguments are collected in kwargs.
Example
def show_details(name, **kwargs):
print("Name:", name)
print("Other details:", kwargs)
show_details("Alice", age=25, city="Delhi")
# Output:
Name: Alice
Other details: {'age': 25, 'city': 'Delhi'}
Explanation: Here, name is a required parameter. The additional keyword arguments, age and city, are collected in kwargs.
2. Parameter Order With **kwargs
**kwargs must be the last parameter in a function definition. No parameter can be placed after it.
Parameters before **kwargs are handled separately, while **kwargs collects the remaining keyword arguments.
Example
def show_details(name, age, **kwargs):
print("Name:", name)
print("Age:", age)
print("Other details:", kwargs)
show_details("Alice", 25, city="Delhi", job="Developer")
# Output:
Name: Alice
Age: 25
Other details: {'city': 'Delhi', 'job': 'Developer'}
Explanation: Here, name and age are regular parameters. The additional keyword arguments, city and job, are collected in kwargs.
3. Multiple Regular Parameters and **kwargs Together
Multiple regular parameters can be defined before **kwargs. The regular parameters receive their values directly, while additional keyword arguments are collected in kwargs.
Example
def show_details(name, age, city, **kwargs):
print("Name:", name)
print("Age:", age)
print("City:", city)
print("Other details:", kwargs)
show_details("Alice", 25, "Delhi", job="Developer", country="India")
# Output:
Name: Alice
Age: 25
City: Delhi
Other details: {'job': 'Developer', 'country': 'India'}
Explanation: Here, name, age, and city are regular parameters. The additional keyword arguments, job and country, are collected in kwargs.
*args vs **kwargs in Python
Python provides *args and **kwargs when a function needs to accept a variable number of arguments. The difference is the type of arguments they collect.
*args collects extra positional arguments in a tuple, while **kwargs collects extra keyword arguments in a dictionary.
*argsfor Positional Arguments**kwargsfor Keyword Arguments- Comparing
*argsand**kwargs - Using
*argsand**kwargsTogether
1. *args for Positional Arguments
*args allows a function to accept any number of positional arguments. Python collects them into a tuple.
Example
def show_values(*args):
print(args)
show_values(10, 20, 30)
# Output:
(10, 20, 30)
Explanation: Here, 10, 20, and 30 are positional arguments. Python collects them in the args tuple.
2. **kwargs for Keyword Arguments
**kwargs allows a function to accept any number of keyword arguments. Python collects them into a dictionary.
Example
def show_details(**kwargs):
print(kwargs)
show_details(name="Alice", age=25, city="Delhi")
# Output:
{'name': 'Alice', 'age': 25, 'city': 'Delhi'}
Explanation: Here, the keyword arguments are collected as key-value pairs in the kwargs dictionary.
3. Comparing *args and **kwargs
*argscollects positional arguments in a tuple.**kwargscollects keyword arguments in a dictionary.
Example
def show_arguments(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
show_arguments(10, 20, name="Alice", age=25)
# Output:
Positional arguments: (10, 20)
Keyword arguments: {'name': 'Alice', 'age': 25}
Explanation: The positional arguments 10 and 20 are collected in args, while the keyword arguments name and age are collected in kwargs.
4. Using *args and **kwargs Together
A function can use *args and **kwargs together when it needs to accept a variable number of both positional and keyword arguments.
Example
def create_product(*features, **details):
print("Features:", features)
print("Details:", details)
create_product(
"Wireless",
"Rechargeable",
price=1500,
brand="TechPro"
)
# Output:
Features: ('Wireless', 'Rechargeable')
Details: {'price': 1500, 'brand': 'TechPro'}
Explanation: The positional arguments are collected in features, while the keyword arguments are collected in details.
When both are used together, *args comes before **kwargs in the function definition.
Passing a Dictionary With **
The double asterisk (**) can also be used in a function call to unpack a dictionary into keyword arguments.
This use of ** is different from **kwargs in a function definition. In a function call, it unpacks dictionary entries; in a function definition, it collects keyword arguments.
Unpacking a Dictionary Into Keyword Arguments
Place ** before a dictionary in a function call to unpack its key-value pairs into keyword arguments.
Example
def show_details(name, age, city):
print("Name:", name)
print("Age:", age)
print("City:", city)
details = {
"name": "Alice",
"age": 25,
"city": "Delhi"
}
show_details(**details)
# Output:
Name: Alice
Age: 25
City: Delhi
Explanation: **details unpacks the dictionary into keyword arguments. The dictionary keys match the function parameters name, age, and city.
** in a Function Call vs **kwargs in a Function Definition
The double asterisk has different roles depending on where it appears. In a function call, ** unpacks a dictionary into keyword arguments. In a function definition, **kwargs collects keyword arguments into a dictionary.
Example
def show_details(**kwargs):
print(kwargs)
details = {
"name": "Alice",
"age": 25
}
show_details(**details)
# Output:
{'name': 'Alice', 'age': 25}
Explanation: Here, **details unpacks the dictionary when the function is called. The **kwargs parameter then collects those keyword arguments into the kwargs dictionary inside the function.
Common Mistakes With **kwargs
Understanding a few common mistakes can help prevent errors when working with **kwargs in Python.
- Forgetting the Double Asterisk
- Treating
kwargsLike a List - Accessing a Missing Key
- Passing Positional Arguments to
**kwargs - Incorrect Parameter Order
1. Forgetting the Double Asterisk
The ** before the parameter name tells Python to collect keyword arguments. Without it, the parameter is a normal parameter.
Example
def show_details(kwargs):
print(kwargs)
show_details(name="Alice", age=25)
# Error:
TypeError
Explanation: Here, kwargs is a regular parameter because the double asterisk is missing. The function does not collect keyword arguments automatically.
2. Treating kwargs Like a List
Python stores the collected arguments in a dictionary, not a list. Dictionary keys must be used to access specific values.
Example
def show_details(**kwargs):
print(kwargs[0])
show_details(name="Alice", age=25)
# Error:
KeyError: 0
Explanation: Here, kwargs[0] looks for a dictionary key named 0. It does not access the first item as list indexing would.
3. Accessing a Missing Key
Accessing a key that does not exist with square brackets raises a KeyError.
Example
def show_details(**kwargs):
print(kwargs["age"])
show_details(name="Alice")
# Error:
KeyError: 'age'
Explanation: The "age" key is not present in kwargs, so accessing it with square brackets raises a KeyError.
Use kwargs.get() when a key may not be present.
4. Passing Positional Arguments to **kwargs
**kwargs collects keyword arguments, not positional arguments. Passing a positional argument to a function that only defines **kwargs raises a TypeError.
Example
def show_details(**kwargs):
print(kwargs)
show_details("Alice")
# Error:
TypeError
Explanation: Here, "Alice" is a positional argument, but the function accepts variable arguments only through **kwargs. Therefore, Python raises a TypeError.
5. Incorrect Parameter Order
**kwargs is the final parameter in a function definition. Placing another parameter after it makes the function definition invalid.
Example
def show_details(**kwargs, name):
print(name, kwargs)
# Error:
SyntaxError
Explanation: Here, name appears after **kwargs, so the function definition is invalid.
Practical Examples With **kwargs
The following examples show how **kwargs in Python can handle different types of optional information.
- Example 1: Creating a User Profile
- Example 2: Configuring Application Settings
- Example 3: Creating Product Details
- Example 4: Passing Optional Function Settings
Example 1: Creating a User Profile
A user profile may contain different optional details. **kwargs lets each function call provide only the details that are available.
Example
def create_profile(**kwargs):
print("User Profile:", kwargs)
create_profile(name="Alice", age=25)
create_profile(name="Bob", age=30, city="Delhi")
# Output:
User Profile: {'name': 'Alice', 'age': 25}
User Profile: {'name': 'Bob', 'age': 30, 'city': 'Delhi'}
Explanation: Each call provides a different set of profile details, which Python collects in the kwargs dictionary.
Example 2: Configuring Application Settings
An application may use different settings depending on the configuration. **kwargs allows each call to provide only the settings it needs.
Example
def configure_app(**kwargs):
print("Settings:", kwargs)
configure_app(theme="dark", language="English")
configure_app(theme="light", notifications=True)
# Output:
Settings: {'theme': 'dark', 'language': 'English'}
Settings: {'theme': 'light', 'notifications': True}
Explanation: Each call passes a different set of settings, and **kwargs collects them into a dictionary.
Example 3: Creating Product Details
Different products may require different details. **kwargs can collect those details without requiring a separate parameter for every possible field.
Example
def create_product(**kwargs):
print("Product:", kwargs)
create_product(name="Laptop", price=55000)
create_product(
name="Phone",
price=30000,
brand="ABC",
color="Black"
)
# Output:
Product: {'name': 'Laptop', 'price': 55000}
Product: {'name': 'Phone', 'price': 30000, 'brand': 'ABC', 'color': 'Black'}
Explanation: Each product can provide a different set of details, and the function collects them through **kwargs.
Example 4: Passing Optional Function Settings
**kwargs can also collect optional settings while the main value is handled by a regular parameter.
Example
def send_message(message, **kwargs):
recipient = kwargs.get("recipient", "Unknown")
priority = kwargs.get("priority", "Normal")
print("Message:", message)
print("Recipient:", recipient)
print("Priority:", priority)
send_message(
"Your order is ready.",
recipient="Alice",
priority="High"
)
# Output:
Message: Your order is ready.
Recipient: Alice
Priority: High
Explanation: Here, message is a regular parameter, while recipient and priority are collected in kwargs. The get() method supplies default values when those settings are not provided.
Key Takeaways: Variable-Length Keyword Arguments
Here are the key points to remember about **kwargs in Python.
**kwargscollects a variable number of keyword arguments.- Python stores the collected keyword arguments in a dictionary.
- The keyword names become dictionary keys, and their values become dictionary values.
- The name
kwargsis conventional; the parameter can have another valid name. **kwargscan be combined with regular parameters and*args.**in a function call can unpack a dictionary into keyword arguments.