`*args` and `**kwargs`
*args collects any extra positional arguments into a tuple, and **kwargs collects any extra keyword arguments into a dictionary. Together they let one function accept a variable number of inputs.
Detailed Explanation
A normal Python function has a fixed set of parameters. def area(width, height) accepts exactly two values. But some functions genuinely cannot know how many inputs they will get. A logging helper might receive one tag or six. A decorator wraps a function whose signature it has never seen. Before this syntax existed, the caller had to pack everything into a list or dict by hand, and every call site paid for that ceremony.
The star is not part of the name. * and ** are packing operators, and args and kwargs are only a naming convention. *extra and **options work identically, and descriptive names are usually better.
In a function definition, *args means "sweep up all remaining positional arguments". You receive a tuple, which is immutable and always present, even when it is empty. **kwargs means "sweep up all remaining keyword arguments". You receive a plain dict, freshly built for each call, so mutating it is safe and affects nobody else. Since Python 3.7 that dict preserves the order the caller used.
At a call site the same symbols do the reverse: they unpack. send(*values) spreads a sequence into separate positional arguments. send(**options) spreads a mapping into separate keyword arguments. You can unpack more than one of each in a single call, as long as no keyword arrives twice.
Parameter order in a definition is fixed: positional parameters, then *args, then keyword-only parameters, then **kwargs. Anything written after *args can only be passed by keyword, which is a useful trick in itself. A bare * with no name forces the rest to be keyword-only, and a / marks the parameters before it as positional-only.
The classic use is forwarding. A wrapper that takes *args, **kwargs and passes them straight through works for any wrapped function, which is why almost every decorator you read is written that way.
The cost is signature clarity. def handle(*args, **kwargs) documents nothing, so editors cannot autocomplete it, type checkers cannot verify calls, and a misspelled keyword lands silently in kwargs rather than raising TypeError. Reach for it when the arity is genuinely open-ended or when you are forwarding. When you know the parameters, write them out.
You can annotate them. *args: int means every positional extra is an int, and **kwargs: str means every keyword extra is a str, so the annotation describes each element rather than the tuple or dict.
Code Examples
# In a definition, * and ** pack the leftovers.
def log_event(event_name, *tags, level="info", **fields):
# tags is a tuple of the extra positional arguments
# fields is a dict of the extra keyword arguments
# level sits after *tags, so it can only be passed by keyword
print(event_name, tags, level, fields)
log_event("login", "auth", "web", level="warning", user_id=42, ip="10.0.0.1")
# login ('auth', 'web') warning {'user_id': 42, 'ip': '10.0.0.1'}
log_event("ping")
# ping () info {} <- an empty tuple and an empty dict, never None# At a call site, * and ** unpack.
def send_email(to, subject, body, *, retries=3):
return f"to={to} subject={subject!r} retries={retries}"
positional = ["ana@example.com", "Welcome"]
options = {"body": "Hello!", "retries": 5}
print(send_email(*positional, **options))
# to=ana@example.com subject='Welcome' retries=5
# Forwarding: the wrapper works for any signature because it inspects nothing.
def with_call_logging(func):
def wrapper(*call_args, **call_kwargs):
print("calling", func.__name__)
return func(*call_args, **call_kwargs) # passed through unchanged
return wrapper
send = with_call_logging(send_email)
print(send("bo@example.com", "Hi", body="yo"))
# calling send_email
# to=bo@example.com subject='Hi' retries=3# / and * control how arguments may be passed.
def clamp(value, /, low=0.0, *, high=1.0):
# value: positional only. low: either. high: keyword only.
return max(low, min(value, high))
print(clamp(1.5, high=2.0)) # 1.5
print(clamp(-4, 0.0, high=2.0)) # 0.0
try:
clamp(value=1.5) # rejected: value is positional-only
except TypeError as exc:
print("boom:", exc)Common Gotchas
An open signature hides typos
a function accepting `**kwargs` takes `timeuot=30` without complaining, and the option is silently ignored. Spell out the parameters you actually support, or validate the keys you received.
Unpacking the same keyword twice fails
`send(**defaults, **overrides)` raises `TypeError: got multiple values for keyword argument` when both dicts share a key. Merge them first with `{**defaults, **overrides}`, where the later value wins.
Bare forwarding breaks introspection
a `*args, **kwargs` wrapper loses the wrapped function's name, docstring, and signature. Apply `functools.wraps` to the wrapper to copy them back.