In a Python function definition, *args collects any extra positional arguments into a tuple, while **kwargs collects any extra keyword arguments into a dict—enabling functions, wrappers, decorators, and subclass overrides to accept a variable number of arguments and forward them cleanly via argument unpacking (func(*args, **kwargs)).
Basic Example
# 1. Accepting arbitrary positional (*args) and keyword (**kwargs) arguments
def log_event(event_name: str, *args, **kwargs) -> None:
print(f"Event: {event_name}")
print(f"Positional args (tuple): {args}")
print(f"Keyword args (dict): {kwargs}")
log_event("purchase", 42, "USD", user="alice", retry=True)
# Output:
# Event: purchase
# Positional args (tuple): (42, 'USD')
# Keyword args (dict): {'user': 'alice', 'retry': True}
# 2. Forwarding arguments inside a wrapper / decorator using unpacking
def trace(fn):
def wrapper(*args, **kwargs):
print(f"Calling {fn.__name__}")
return fn(*args, **kwargs) # Unpacks tuple & dict back into individual args
return wrapper
Key Details & Edge Cases
- The
*and**operators do the actual work—the namesargsandkwargsare only PEP 8 conventions:- You can legally name them
*itemsand**options(def build(*items, **options):), thoughargsandkwargsare universally expected by readers and linters.
- You can legally name them
- Strict parameter ordering in function definitions (
SyntaxErrorif violated):- Python enforces a fixed parameter order:
def func(pos_only, /, standard, *args, kw_only, **kwargs): - Placing
*argsafter**kwargsor placing standard positional parameters after*args(which turns them into keyword-only parameters!) changes call semantics or raises aSyntaxError.
- Python enforces a fixed parameter order:
- Bare
*without a variable name (def connect(host, *, timeout=5):):- Writing a standalone
*with no identifier after it discards any extra positional arguments (raisingTypeErrorif too many positional arguments are passed) and forces all subsequent parameters to be passed strictly as keyword-only arguments.
- Writing a standalone
*argsis always atuple(immutable) and**kwargsis always a freshdict:- Even when zero extra arguments are supplied,
argsdefaults to()(notNone) andkwargsdefaults to{}(notNone)—so iteratingfor x in args:or callingkwargs.get("key")is always safe withoutNonechecks. - Modifying
kwargsinside the function (kwargs.pop("debug", False)) mutates only the local dictionary created for that call, never the caller’s dictionary.
- Even when zero extra arguments are supplied,
- Type-annotating
*argsand**kwargs(PEP 484 / PEP 692):- Annotate homogeneous extra arguments by element/value type:
def fn(*args: int, **kwargs: str) -> None:(meaningargsistuple[int, ...]andkwargsisdict[str, str]). For heterogeneously typed keyword arguments in Python 3.12+, usetyping.Unpackwith aTypedDict(**kwargs: Unpack[RequestOptions]).
- Annotate homogeneous extra arguments by element/value type:
Comparison of *args, **kwargs, and Related Parameter Syntax
Syntax in def |
Collected Type | Default When Omitted | Accepts | Best Used When |
|---|---|---|---|---|
*args |
tuple |
() (empty tuple) |
Arbitrary extra positional arguments | Functions taking variable inputs (sum_all(*nums)) or forwarding calls in wrappers. |
**kwargs |
dict[str, Any] |
{} (empty dict) |
Arbitrary extra key=value keyword arguments |
Passing optional configuration flags through to underlying libraries or super().__init__(). |
*args, **kwargs |
tuple + dict |
() and {} |
Any combination of positional and keyword arguments | Decorators, proxy wrappers, and subclass method overrides forwarding all arguments. |
Bare * |
None (no variable bound) | N/A | Rejects extra positional args; forces keyword-only after * |
Designing clean APIs where optional flags cannot be passed accidentally by position. |
Forwarding fn(*a, **kw) |
Unpacks iterable & mapping | N/A | Expands sequence into positional args & dict into keyword args | Delegating captured arguments to another function call. |
You must log in or register to comment.
