Skip to content

Python * and ** unpacking: *args, **kwargs and more

  • The four places * and ** appear: function definitions, function calls, list/set/dict displays and assignment targets.
  • The parameter order rules and what *args (a tuple) and **kwargs (a dict) actually contain.
  • How duplicate keys behave differently in a call (error) and in a dict display (last one wins).
  • How to forward arguments in a decorator, and how Unpack[TypedDict] gives **kwargs real type checking.
  • The traps: typos swallowed by **kwargs, exhausted generators, non-string keys and lone starred targets.

“Splat” is the informal name for Python’s * and ** prefixes. In a function definition they collect: *args gathers extra positional arguments into a tuple and **kwargs gathers extra keyword arguments into a dict. In a call or a display ([...], {...}) they unpack: *iterable spreads items out and **mapping spreads key-value pairs. In an assignment target, *rest captures whatever is left over as a list. The collecting forms date back to early Python; extended unpacking arrived in 3.0 (PEP 3132) and multiple unpackings in 3.5 (PEP 448). All of it is current in Python 3.14.

Without variadic parameters, a function that accepts “any number of SKUs” forces every caller to build a list first, and a function that passes options through to another layer must list every option by name. OrdersPortal’s reservation helper shows both sides.

Running the samples: each sample is a complete script. Save it as a .py file and run it with Python 3.14 (python3 sample.py). Outputs shown were produced with CPython 3.14.6. Lines that need a version newer than 3.5 are marked.

# Before: callers must build a container just to pass several SKUs.
def reserve_list(order_id, skus, options):
return f"{order_id}: {skus} {options}"
print(reserve_list("ORD-1001", ["MUG-01", "TEE-04"], {"warehouse": "east"}))
# After: *skus collects extra positionals, **options collects extra keywords.
def reserve(order_id, *skus, **options):
return f"{order_id}: {skus} {options}"
print(reserve("ORD-1001", "MUG-01", "TEE-04", warehouse="east"))
print(reserve("ORD-1002"))
# The same symbols at a call site unpack instead of collect.
cart = ["PEN-02", "CAP-07"]
prefs = {"warehouse": "west", "gift_wrap": True}
print(reserve("ORD-1003", *cart, **prefs))

Output:

ORD-1001: ['MUG-01', 'TEE-04'] {'warehouse': 'east'}
ORD-1001: ('MUG-01', 'TEE-04') {'warehouse': 'east'}
ORD-1002: () {}
ORD-1003: ('PEN-02', 'CAP-07') {'warehouse': 'west', 'gift_wrap': True}

The collected values are always fresh containers: skus is a tuple (empty when nothing extra was passed) and options is a new dict, so mutating options inside the function never changes the caller’s prefs.

# 1. Definitions: the full parameter order.
def ship(order_id, /, carrier, *parcels, express=False, **meta):
print(order_id, carrier, parcels, express, meta)
ship("ORD-1", "ups", "box-1", "box-2", express=True, note="fragile")
# 2. Calls: any number of * and ** unpackings (Python 3.5+).
flags = {"express": True}
meta = {"note": "leave at door"}
ship("ORD-2", "dhl", *["box-1"], *("box-2",), **flags, **meta)
try:
ship("ORD-3", "ups", **flags, **{"express": False})
except TypeError as exc:
print("TypeError:", exc)
# 3. Displays: build lists, sets and dicts (Python 3.5+).
defaults = {"currency": "EUR", "warehouse": "east"}
override = {"warehouse": "west"}
print([*"AB", *range(2)], sorted({*"aba", *"bc"}), {**defaults, **override})
# 4. Assignment: a starred target always gets a list (Python 3.0+).
first, *middle, last = ("ORD-1", "ORD-2", "ORD-3", "ORD-4")
print(first, middle, last)
head, *rest = "A"
print(head, rest)
# 5. Return and for statements accept starred items unparenthesized.
def summary(order_id, *totals):
return order_id, *totals
print(summary("ORD-5", 10, 20))
morning, evening = ["MUG-01"], ["PEN-02", "CAP-07"]
for sku in *morning, *evening: # Python 3.11+
print(sku)

Output:

ORD-1 ups ('box-1', 'box-2') True {'note': 'fragile'}
ORD-2 dhl ('box-1', 'box-2') True {'note': 'leave at door'}
TypeError: __main__.ship() got multiple values for keyword argument 'express'
['A', 'B', 0, 1] ['a', 'b', 'c'] {'currency': 'EUR', 'warehouse': 'west'}
ORD-1 ['ORD-2', 'ORD-3'] ORD-4
A []
('ORD-5', 10, 20)
MUG-01
PEN-02
CAP-07

The rules behind each part:

  • Definitions. The order is: positional-only parameters, /, ordinary parameters, *args (or a bare *), keyword-only parameters, **kwargs. Anything after *args can only be passed by name, which is how express becomes keyword-only. There can be at most one * and one ** parameter, and **kwargs must be last. The names args and kwargs are convention only.
  • Calls. *iterable accepts any iterable and adds its items as positional arguments; **mapping needs a mapping with string keys and adds keyword arguments. Since 3.5 a call may contain several of each, and the language reference notes that * unpackings are processed before keyword arguments even when written after them. If two sources supply the same parameter, the call fails with TypeError rather than picking one.
  • Displays. Inside [...], (...), {...} and dict displays the rule is the opposite: a later key silently wins. {**defaults, **override} is the classic “defaults plus overrides” merge. Since 3.9, defaults | override does the same for two dicts.
  • Assignment. One starred target per assignment, and it always receives a list, possibly empty. The right-hand side can be any iterable.
  • Statements. return a, *rest and yield a, *rest have worked without parentheses since 3.8; starred items in a for header since 3.11.

Python 3.15, in development at the time of writing, adds unpacking inside comprehensions (PEP 798), such as [*batch for batch in batches] to flatten a list of lists. Until 3.15 is released, use itertools.chain.from_iterable or a nested comprehension.

OrdersPortal’s API client has a logging decorator that must work for any function, and a get() function that takes a variable list of query fragments plus optional request settings. The settings are typed with Unpack[TypedDict] so a type checker can see exactly which keywords are allowed.

import functools
from typing import TypedDict, Unpack
class RequestOptions(TypedDict, total=False):
timeout: float
retries: int
headers: dict[str, str]
DEFAULTS: RequestOptions = {"timeout": 5.0, "retries": 2, "headers": {"Accept": "application/json"}}
def logged(func):
"""Decorator: forwards any arguments unchanged with *args/**kwargs."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
shown = [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()]
print(f"-> {func.__name__}({', '.join(shown)})")
return func(*args, **kwargs)
return wrapper
@logged
def get(path: str, /, *query: str, **options: Unpack[RequestOptions]) -> dict:
# Later keys win: caller options override DEFAULTS, and headers merge too.
merged = {**DEFAULTS, **options}
merged["headers"] = {**DEFAULTS["headers"], **options.get("headers", {})}
url = "https://api.example.test" + path + ("?" + "&".join(query) if query else "")
return {"url": url, **merged}
print(get("/orders", "status=open", "page=2", timeout=1.5))
print(get("/orders/ORD-1001", headers={"X-Trace": "abc123"}))
# Forward a stored configuration with ** at the call site.
saved = {"retries": 5}
print(get("/health", **saved)["retries"])
print(get.__name__, get.__wrapped__.__name__)

Output:

-> get('/orders', 'status=open', 'page=2', timeout=1.5)
{'url': 'https://api.example.test/orders?status=open&page=2', 'timeout': 1.5, 'retries': 2, 'headers': {'Accept': 'application/json'}}
-> get('/orders/ORD-1001', headers={'X-Trace': 'abc123'})
{'url': 'https://api.example.test/orders/ORD-1001', 'timeout': 5.0, 'retries': 2, 'headers': {'Accept': 'application/json', 'X-Trace': 'abc123'}}
-> get('/health', retries=5)
5
get get

Three idioms appear here. The decorator’s def wrapper(*args, **kwargs): return func(*args, **kwargs) forwards any call shape unchanged, and functools.wraps keeps the name and __wrapped__. {**DEFAULTS, **options} is a one-line merge where the caller wins, and the nested headers dict is merged separately because ** merging is shallow. Finally, Unpack[RequestOptions] (PEP 692, Python 3.12) tells type checkers which keyword arguments **options accepts. With mypy 2.4 a typo is caught statically, while an untyped **options accepts it silently (save as typed_kwargs.py and run mypy typed_kwargs.py):

from typing import TypedDict, Unpack
class RequestOptions(TypedDict, total=False):
timeout: float
retries: int
def get(path: str, /, **options: Unpack[RequestOptions]) -> None: ...
def get_untyped(path: str, /, **options: object) -> None: ...
get("/orders", timout=1.5) # typo
get_untyped("/orders", timout=1.5) # typo, silently accepted

mypy output (the script itself runs without error, because annotations are not enforced at run time):

typed_kwargs.py:11: error: Unexpected keyword argument "timout" for "get"; did you mean "timeout"? [call-arg]
Found 1 error in 1 file (checked 1 source file)
# 1. ** needs string keys.
def tag(**labels):
return labels
try:
tag(**{1: "first"})
except TypeError as exc:
print("TypeError:", exc)
# 2. Unpacking a generator consumes it.
skus = (s.upper() for s in ["mug-01", "pen-02"])
print([*skus], [*skus])
# 3. Unpacking a dict with * gives its keys.
order = {"id": "ORD-1", "total": 9.5}
print(*order)
# 4. A lone starred target needs a trailing comma or list brackets.
for src in ("*rest = [1, 2]", "*rest, = [1, 2]"):
try:
exec(src)
print(src, "->", "OK")
except SyntaxError as exc:
print(src, "->", "SyntaxError:", exc.msg)
# 5. **kwargs silently swallows typos.
def create_order(customer, *, express=False, **extra):
return express
print(create_order("ada", exprss=True)) # typo: express stays False

Output:

TypeError: keywords must be strings
['MUG-01', 'PEN-02'] []
id total
*rest = [1, 2] -> SyntaxError: starred assignment target must be in a list or tuple
*rest, = [1, 2] -> OK
False
  • Non-string keys with **. Keyword arguments are names, so **{1: "x"} fails. Use a plain dict parameter for data keyed by IDs.
  • Unpacking an iterator twice. * consumes generators, file objects and map results; the second unpacking is empty. Materialize once with list() if you need it again.
  • Expecting values from *some_dict. Iterating a dict yields keys. Use *d.values() or *d.items().
  • A lone starred target. *rest = items is a SyntaxError; write rest = list(items) or *rest, = items.
  • **kwargs as a catch-all in public APIs. A misspelled option disappears into extra and the default silently applies. Prefer explicit keyword-only parameters, or reject unknown keys, or type **kwargs with Unpack[TypedDict].
  • Assuming {**a, **b} merges deeply. Nested dicts are replaced, not merged, and the copy is shallow: the nested objects are shared with the originals.
  • Forwarding without functools.wraps. A wrapper built on *args, **kwargs hides the wrapped function’s name, docstring and signature from help() and inspect.signature() unless you apply wraps.

Use *args when callers naturally pass a variable number of values of the same kind (max(a, b, c), a list of SKUs). Use **kwargs when forwarding options to another layer or accepting genuinely open-ended metadata. Prefer explicit, named, keyword-only parameters whenever you know the options in advance: they document themselves, they show up in help(), and typos fail loudly.

Goal Prefer
Variable number of same-kind values def f(*items)
Forward any call shape (decorator, proxy) def wrapper(*args, **kwargs) + functools.wraps
A known set of options Keyword-only parameters after *
Known options that must pass through **kwargs **kwargs: Unpack[TypedDict] (3.12+)
Merge two dicts, right side wins {**a, **b} or a | b (3.9+)
Split first item from the rest first, *rest = items
Flatten many iterables lazily itertools.chain.from_iterable
Version Change
Before 3.0 *args, **kwargs and call-site unpacking, at most one * and one ** per call.
3.0 Extended iterable unpacking in assignments, first, *rest = ... (PEP 3132); keyword-only parameters after *args (PEP 3102).
3.5 Any number of */** unpackings in calls; unpacking in tuple, list, set and dict displays (PEP 448).
3.8 return a, *rest and yield a, *rest without parentheses; positional-only / (PEP 570).
3.9 Dict union operators | and |=, an alternative to {**a, **b}.
3.11 Starred items in for statements; * in subscripts for variadic generics (PEP 646).
3.12 Unpack[TypedDict] for precise **kwargs typing (PEP 692).
3.15 (in development) Unpacking in comprehensions and generator expressions (PEP 798).

1. What types are args and kwargs inside def f(*args, **kwargs), and are they shared with the caller? args is a tuple and kwargs is a new dict, both built for that call. They are never the caller’s own containers, so mutating kwargs is safe; the values inside are the same objects, though, so mutating a list passed as an argument is visible to the caller.

2. Why does f(**a, **b) raise TypeError when the dicts share a key, while {**a, **b} does not? A call binds each key to a parameter, and binding the same parameter twice is an error by design, so the language reference raises TypeError. A dict display simply inserts keys in order, so later values overwrite earlier ones; that is what makes it useful for merging defaults and overrides.

3. What does first, *rest = "A" give, and what is the type of rest for a tuple on the right? first is "A" and rest is []. A starred assignment target is always a list, whatever iterable is on the right-hand side, including a tuple or a string.

4. Senior scenario: OrdersPortal’s SDK has create_order(customer, **options) and support tickets show customers passing expres=True and wondering why orders ship slowly. How do you fix it without breaking existing callers? The root cause is an open **options that swallows typos. Replace it with explicit keyword-only parameters for the known options (*, express=False, gift_wrap=False). To stay compatible, keep **options for one release, but check its keys against an allowed set and raise TypeError (or emit a DeprecationWarning first) for unknown ones, using difflib.get_close_matches to suggest the intended name. If the options must stay in **kwargs because they are forwarded to another layer, type them with Unpack[TypedDict] so type checkers flag typos, and add a run-time check at the boundary, since annotations are not enforced.

  • In definitions * and ** collect (tuple and dict); in calls and displays they unpack; in assignment targets *rest captures a list.
  • Duplicate keys raise TypeError in a call but silently take the last value in a dict display.
  • Use *args, **kwargs plus functools.wraps for forwarding wrappers, not as a substitute for named parameters.
  • Unpack[TypedDict] (3.12) brings static checking to **kwargs.
  • Watch for exhausted iterators, shallow merges and typos disappearing into **kwargs.