Python *args and **kwargs
When designing flexible functions, you often encounter situations where you don't know in advance how many arguments will be passed. Python solves this using *args (arbitrary positional arguments) and **kwargs (arbitrary keyword arguments).
1. *args: Variable Positional Arguments
The single asterisk (*) collects any number of extra positional arguments passed into a function and packs them into a tuple.
While the name args is a convention (you could technically name it *numbers or *items), the * prefix is what Python recognizes.
def calculate_total(*args):
print(type(args)) # Output: <class 'tuple'>
total = sum(args)
return total
print(calculate_total(10, 20, 30)) # Output: 60
print(calculate_total(5, 10, 15, 20, 25)) # Output: 75
Unpacking Collections with *
You can also use the * operator when calling a function to unpack a list or tuple into individual positional arguments:
numbers = [4, 8, 15, 16, 23, 42]
# Without unpacking, sum() would see a single list argument
# With unpacking, it passes 6 separate arguments
print(calculate_total(*numbers)) # Output: 108
2. **kwargs: Variable Keyword Arguments
The double asterisk (**) collects any number of extra keyword arguments (key-value pairs) and packs them into a standard Python dictionary.
The name kwargs stands for "keyword arguments".
def print_user_profile(**kwargs):
print(type(kwargs)) # Output: <class 'dict'>
for key, value in kwargs.items():
print(f"{key}: {value}")
print_user_profile(username="alex99", email="alex@example.com", role="Admin")
Unpacking Dictionaries with **
Similarly, you can unpack a dictionary into keyword arguments when calling a function:
user_data = {"name": "Sara", "age": 28, "location": "Berlin"}
def greet_user(name, age, location):
print(f"Hello {name}, age {age} from {location}!")
greet_user(**user_data) # Output: Hello Sara, age 28 from Berlin!
3. Combining Standard Parameters, *args, and **kwargs
You can use standard parameters, *args, and **kwargs in the same function definition. However, Python enforces a strict parameter order to avoid ambiguity:
- Standard positional parameters
*args(Variable positional arguments)- Keyword-only parameters (or default arguments)
**kwargs(Variable keyword arguments)
def flexible_function(title, *args, debug=False, **kwargs):
print(f"Title: {title}")
print(f"Positional args tuple: {args}")
print(f"Debug flag: {debug}")
print(f"Keyword args dict: {kwargs}")
flexible_function(
"Report",
100, 200, 300,
debug=True,
author="Alice",
version=2
)