Python *args and **kwargs
Satellite · Functions
Python *args and **kwargs
Leverage variadic parameters to build extensible functions and wrappers.
Examples
def log_event(event_type, *details, **meta):
print(event_type, details, meta)
log_event("login", "user123", ip="1.1.1.1")
*detailsbecomes a tuple of extra positional arguments.**metabecomes a dict of keyword arguments.
Forwarding arguments
def with_retry(func):
def wrapper(*args, **kwargs):
for _ in range(3):
try:
return func(*args, **kwargs)
except Exception:
continue
return wrapper
Best practices
- Keep required parameters explicit. Move
*args/**kwargsto the end. - Document accepted arguments in docstrings even if they're flexible.
- Avoid swallowing unexpected keywords silently; validate them when possible.