Python * and ** unpacking: *args, **kwargs and more
What you’ll learn
Section titled “What you’ll learn”- 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**kwargsreal type checking. - The traps: typos swallowed by
**kwargs, exhausted generators, non-string keys and lone starred targets.
Summary
Section titled “Summary”“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.
The problem it solves
Section titled “The problem it solves”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.
How it works
Section titled “How it works”# 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, *totalsprint(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-4A []('ORD-5', 10, 20)MUG-01PEN-02CAP-07The rules behind each part:
- Definitions. The order is: positional-only parameters,
/, ordinary parameters,*args(or a bare*), keyword-only parameters,**kwargs. Anything after*argscan only be passed by name, which is howexpressbecomes keyword-only. There can be at most one*and one**parameter, and**kwargsmust be last. The namesargsandkwargsare convention only. - Calls.
*iterableaccepts any iterable and adds its items as positional arguments;**mappingneeds 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 withTypeErrorrather 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 | overridedoes 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, *restandyield a, *resthave worked without parentheses since 3.8; starred items in aforheader 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.
Realistic example
Section titled “Realistic example”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 functoolsfrom 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
@loggeddef 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)5get getThree 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) # typoget_untyped("/orders", timout=1.5) # typo, silently acceptedmypy 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)Common mistakes
Section titled “Common mistakes”# 1. ** needs string keys.def tag(**labels): return labelstry: 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 expressprint(create_order("ada", exprss=True)) # typo: express stays FalseOutput:
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] -> OKFalse- 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 andmapresults; the second unpacking is empty. Materialize once withlist()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 = itemsis aSyntaxError; writerest = list(items)or*rest, = items. **kwargsas a catch-all in public APIs. A misspelled option disappears intoextraand the default silently applies. Prefer explicit keyword-only parameters, or reject unknown keys, or type**kwargswithUnpack[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, **kwargshides the wrapped function’s name, docstring and signature fromhelp()andinspect.signature()unless you applywraps.
When to use it and when not to
Section titled “When to use it and when not to”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 |
Compatibility
Section titled “Compatibility”| 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). |
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”- In definitions
*and**collect (tuple and dict); in calls and displays they unpack; in assignment targets*restcaptures a list. - Duplicate keys raise
TypeErrorin a call but silently take the last value in a dict display. - Use
*args, **kwargsplusfunctools.wrapsfor 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.
Related pages
Section titled “Related pages”- Keyword-only parameters: the bare
*marker and parameters after*args. - Positional-only parameters: the
/marker in the parameter order. - zip():
zip(*rows)to transpose, a classic use of call-site unpacking. - Python decorators: wrappers that forward
*argsand**kwargs. - Functions: parameters, defaults and calling conventions.
- Type hints: annotating
*argsand**kwargs. - Dictionaries: merging with
**and|.
Official references
Section titled “Official references”- Tutorial: Arbitrary argument lists and unpacking argument lists (Python 3.14)
- Language reference: Calls (Python 3.14)
- Language reference: Expression lists and iterable unpacking (Python 3.14)
- Language reference: Assignment statements (Python 3.14)
- typing.Unpack (Python 3.14 docs)
- What’s New in Python 3.5: PEP 448
- PEP 3132: Extended Iterable Unpacking
- PEP 448: Additional Unpacking Generalizations
- PEP 692: Using TypedDict for more precise **kwargs typing
- PEP 798: Unpacking in Comprehensions