Table Of Contents
Problem
You need to create functions that accept a variable number of arguments or keyword arguments without knowing the exact count beforehand.
Solution
# *args for variable positional arguments
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3)) # 6
print(sum_numbers(1, 2, 3, 4, 5)) # 15
# **kwargs for variable keyword arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="John", age=25, city="NYC")
# name: John
# age: 25
# city: NYC
# Combine regular args, *args, and **kwargs
def flexible_function(required, *args, **kwargs):
print(f"Required: {required}")
print(f"Args: {args}")
print(f"Kwargs: {kwargs}")
flexible_function("hello", 1, 2, 3, name="Alice", age=30)
# Required: hello
# Args: (1, 2, 3)
# Kwargs: {'name': 'Alice', 'age': 30}
# Unpacking when calling functions
def greet(first, last, age):
print(f"Hello {first} {last}, age {age}")
person_tuple = ("John", "Doe", 25)
person_dict = {"first": "Jane", "last": "Smith", "age": 30}
greet(*person_tuple) # Hello John Doe, age 25
greet(**person_dict) # Hello Jane Smith, age 30
# Practical example: flexible logger
def log_message(level, message, **kwargs):
print(f"[{level}] {message}")
if kwargs:
print(f"Additional info: {kwargs}")
log_message("INFO", "User logged in", user_id=123, ip="192.168.1.1")
# [INFO] User logged in
# Additional info: {'user_id': 123, 'ip': '192.168.1.1'}
# Function wrapper example
def debug_function(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
result = func(*args, **kwargs)
print(f"Result: {result}")
return result
return wrapper
@debug_function
def multiply(x, y):
return x * y
multiply(3, 5) # Shows debug info + result
Explanation
*args
collects extra positional arguments into a tuple. **kwargs
collects extra keyword arguments into a dictionary. Use them to create flexible functions.
When calling functions, *
unpacks sequences and **
unpacks dictionaries. This pattern is essential for decorators and wrapper functions.
Share this article
Add Comment
No comments yet. Be the first to comment!