Skip to main content

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")
  • *details becomes a tuple of extra positional arguments.
  • **meta becomes 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/**kwargs to the end.
  • Document accepted arguments in docstrings even if they're flexible.
  • Avoid swallowing unexpected keywords silently; validate them when possible.

Next up in your learning path