Sub topic 10
Collecting extra arguments with *args and **kwargs
This chapter assumes you can define and call functions, know how default values and keyword arguments work, and have read the earlier chapters on parameter ordering and the * and / markers. You should also be comfortable with tuples and dicts.
What the stars do in a definition
A parameter written with one star, such as *args, collects every extra positional argument into a tuple. A parameter written with two stars, such as **kwargs, collects every extra keyword argument into a dict. "Extra" means the argument did not match any other named parameter.
The names args and kwargs are only conventions. The stars create the behavior, so *numbers and **options work the same way.
def total(*numbers):
return sum(numbers)
def show(*args):
print(type(args), args)
print(total()) # 0
print(total(1, 2, 3)) # 6
show(1, "a") # <class 'tuple'> (1, 'a')With no extra arguments, args is an empty tuple, never None. You can loop over it without a guard.
def tag(name, **attrs):
pairs = " ".join(f'{k}="{v}"' for k, v in attrs.items())
return f"<{name} {pairs}>" if pairs else f"<{name}>"
print(tag("a", href="https://example.com", target="_blank"))
# <a href="https://example.com" target="_blank">
print(tag("br")) # <br>With no extra keywords, attrs is an empty dict.
How a call is bound
Python binds arguments in a fixed order. It fills positional parameters from left to right. Surplus positional values go to *args. Keyword arguments are matched by name. Any keyword that matches no parameter goes to **kwargs. Defaults fill whatever is still empty.
Here is the full signature in code:
def f(a, b=2, *args, c=3, **kwargs):
return a, b, args, c, kwargs
print(f(1)) # (1, 2, (), 3, {})
print(f(1, 10, 20, 30, c=4, x=5)) # (1, 10, (20, 30), 4, {'x': 5})
print(f(1, c=9)) # (1, 2, (), 9, {})Once *args appears, every parameter after it is keyword-only. That is why c needs no bare * here: *args already acts as the marker. In the second call, 20 and 30 can never reach c, because positional arguments stop at *args.
Where the stars may appear
| Position in the signature | Allowed content | Notes |
|---|---|---|
| Before `/` | Positional-only parameters | Optional section |
| Between `/` and `*` | Normal parameters | Positional or keyword |
| `*args` or bare `*` | At most one of these | Starts the keyword-only section |
| After `*args` | Keyword-only parameters | Defaults may be mixed with required ones in any order |
| Last: `**kwargs` | At most one, and nothing after it | No trailing comma problems in modern Python |
Breaking these rules is a SyntaxError at definition time. Examples are def f(**kw, a) and def f(*a, *b). You cannot combine a bare * with *args, because *args already does that job.
Name collisions between keywords and parameters
A keyword argument whose name matches a named parameter binds to that parameter. It never reaches **kwargs. If the same parameter also received a positional value, the call fails.
def f2(a, **kw):
return a, kw
print(f2(1, b=2)) # (1, {'b': 2})
# f2(1, a=2) # TypeError: f2() got multiple values for argument 'a'Positional-only parameters behave differently. Because a positional-only name cannot be passed by keyword, the same name is free to appear in **kwargs.
def g(a, /, **kw):
return a, kw
print(g(1, a=2)) # (1, {'a': 2})This is a real design reason to use /. A function like dict.update style helpers can accept arbitrary keys, including ones named self or a, without clashing with their own parameters.
Properties worth knowing
argsis a new tuple on every call. Mutating it is impossible, and rebinding the nameargsinside the function has no effect outside.kwargsis a new dict on every call, even when you call with**some_dict. Changing it does not change the caller's dict.kwargskeeps the order in which the keywords were written in the call.- Keys in
kwargsare always strings.
def mutate(**kw):
kw["x"] = 1
def order(**kw):
return list(kw)
d = {}
mutate(**d)
print(d) # {}
print(order(b=1, a=2)) # ['b', 'a']Forwarding arguments to another function
The most common use of both stars together is a wrapper that passes everything through unchanged. The wrapper does not need to know the signature of the function it wraps.
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__} with {args} {kwargs}")
return func(*args, **kwargs)
return wrapper
@log_calls
def area(width, height=1):
return width * height
print(area(3, height=4))
# calling area with (3,) {'height': 4}
# 12The *args and **kwargs in the call to func unpack the tuple and dict back into separate arguments. Because the wrapper preserves the split between positional and keyword arguments, func sees the call exactly as the caller wrote it.
functools.wraps copies the name, docstring, and a __wrapped__ reference onto the wrapper. Without it, introspection tools see only (*args, **kwargs).
Subclass and extension patterns
A subclass that adds one parameter and forwards the rest to its parent uses the same idea:
class Base:
def __init__(self, name, *, debug=False):
self.name = name
self.debug = debug
class Child(Base):
def __init__(self, *args, level=1, **kwargs):
super().__init__(*args, **kwargs)
self.level = level
c = Child("job", debug=True, level=3)
print(c.name, c.debug, c.level) # job True 3level is keyword-only, so it is never mistaken for one of the parent's positional values.
Costs and failure modes
Typos disappear silently. A function that accepts **options takes any keyword, including a misspelled one.
def make_user(name, **options):
return {"name": name, "admin": options.get("admin", False)}
print(make_user("Ada", admn=True)) # {'name': 'Ada', 'admin': False}Nothing raises an error, and the user is not an admin. If you know the valid options, name them as keyword-only parameters, or check kwargs against an allowed set and raise TypeError for the leftovers.
The signature stops documenting itself. help(make_user) shows **options and tells the reader nothing about valid keys. Document them in the docstring, or prefer explicit parameters.
Keyword-only parameters can be required. A parameter after *args with no default must be supplied by name:
def h(*args, x):
return args, x
print(h(1, 2, x=3)) # ((1, 2), 3)
# h(1, 2) # TypeError: h() missing 1 required keyword-only argument: 'x'Unpacking a dict needs string keys. Calling f(**{1: "a"}) raises a TypeError, because keyword names must be strings. Passing the same key twice, for example f(**d1, **d2) where both contain "x", also raises TypeError.
A quick decision guide
| Situation | Choice |
|---|---|
| Function takes any number of equal items, like `max` or `print` | `*items` |
| Wrapper or decorator forwarding to another callable | `*args, **kwargs` |
| Subclass adding one option | Named keyword-only parameter plus `*args, **kwargs` forwarding |
| Known, fixed set of options | Explicit keyword-only parameters |
| Open-ended attributes, such as HTML tag attributes | `**attrs` |
Exercise
What does this code print, and why? def f(x, args, y=0, *kwargs): return x, args, y, kwargs print(f(1, 2, 3, y=4, z=5)) print(f(y=1, x=2))
Show answer
The first call prints (1, (2, 3), 4, {'z': 5}). The value 1 binds to x, the surplus positional values 2 and 3 go to args, y matches by name, and z matches no parameter, so it lands in kwargs. The second call prints (2, (), 1, {}). Keyword arguments can bind x by name, args stays an empty tuple, and kwargs stays an empty dict.
Exercise
Write a decorator called count_calls that wraps any function, forwards all its arguments unchanged, and stores the number of calls in an attribute named calls on the wrapper. Why must the wrapper use both args and *kwargs?
Show answer
Example: import functools def count_calls(func): @functools.wraps(func) def wrapper(args, kwargs): wrapper.calls += 1 return func(args, kwargs) wrapper.calls = 0 return wrapper The wrapper does not know the signature of func. *args captures positional arguments and kwargs captures keyword arguments. Unpacking both in the call to func reproduces the original call exactly. With only *args, any call that passed a keyword argument would raise a TypeError in the wrapper.