*args and **kwargs in Python
What Are *args and **kwargs in Python?
In Python, *args and **kwargs allow you to pass a variable number of arguments to a function.
Keyword | Stands For | Used For |
---|---|---|
*args | Non-keyword arguments | Pass multiple positional arguments |
**kwargs | Keyword arguments | Pass multiple named (key-value) arguments |
Using *args in Python
Definition:
*args allows a function to accept any number of positional arguments (as a tuple).
Syntax:
def function_name(*args):
for arg in args:
print(arg)
Example:
def print_numbers(*args):
for number in args:
print(number)
print_numbers(1, 2, 3, 4)
Output:
1 2 3 4
Using **kwargs in Python
Definition:
**kwargs allows a function to accept any number of keyword arguments (as a dictionary).
Syntax:
def function_name(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")
Example:
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
Output:
name: Alice age: 25 city: New York
Combine *args and **kwargs
You can use both in the same function to handle all kinds of arguments.
Example:
def display_data(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
display_data(10, 20, name="John", age=30)
Output:
Args: (10, 20) Kwargs: {'name': 'John', 'age': 30}
Important Rules
- *args must come before **kwargs in the function definition
- The order should be:
def func(positional, *args, keyword=default, **kwargs):
Real-World Use Case Example
Logging Any Message
def log_message(*args, **kwargs):
print("Log:", *args)
if kwargs:
print("Metadata:")
for k, v in kwargs.items():
print(f"{k} = {v}")
log_message("User login", user="admin", status="success")
Output:
Log: User login Metadata: user = admin status = success
When to Use *args and **kwargs
Use Case | Use |
---|---|
Unknown number of inputs | *args |
Dynamic keyword/value pairs (like JSON) | **kwargs |
Flexible APIs or decorators | Both |
Wrapper functions | *args, **kwargs |