Sub topic 10
Collecting extra arguments with *args and **kwargs
This chapter assumes you can define and call functions, know that defaults and keyword-only parameters exist, and can read a simple traceback. Here you will learn how a function can accept any number of extra arguments.
Why collect extra arguments
Some functions cannot know in advance how many arguments callers will pass. print accepts any number of values. A wrapper function often needs to pass along whatever it receives. Python handles both cases with two special parameters: *args and **kwargs.
*args collects extra positional arguments
A parameter written with one star gathers all extra positional arguments into a tuple. args is only a convention. The star is what matters.
**kwargs collects extra keyword arguments
A parameter written with two stars gathers all extra keyword arguments into a dict. The keys are the argument names as strings.
def describe(*args, **kwargs):
return args, kwargs
print(describe()) # ((), {})
print(describe(1, 2, a=3)) # ((1, 2), {'a': 3})
print(describe("x", mode="fast", retries=2))
# (('x',), {'mode': 'fast', 'retries': 2})If no extra arguments are passed, args is an empty tuple and kwargs is an empty dict. Neither is ever None.
Mixing them with named parameters
Named parameters bind first. Only what is left over goes into the collectors.
def log(level, *messages, sep=" ", **context):
text = sep.join(messages)
return f"[{level}] {text} {context}"
print(log("INFO", "started", "worker", sep="-", pid=42))
# [INFO] started-worker {'pid': 42}Here level takes the first positional argument. The remaining positional arguments go into messages. Because sep comes after *messages, it is keyword-only. Anything that is not sep ends up in context.
The binding steps are:
Ordering rules
In a definition, the order is fixed:
- Regular parameters, with or without defaults
*args- Keyword-only parameters
**kwargs
**kwargs must be last. Once *args appears, every parameter after it is keyword-only, so a bare * is not needed in that case.
Forwarding arguments
The most common use of the collectors is passing arguments through to another function. Combined with unpacking in the call, a wrapper can stay unaware of the details.
def connect(host, port=5432, *, timeout=10):
return (host, port, timeout)
def logged_connect(*args, **kwargs):
print("connecting with", args, kwargs)
return connect(*args, **kwargs)
print(logged_connect("db.local", timeout=5))
# connecting with ('db.local',) {'timeout': 5}
# ('db.local', 5432, 5)The wrapper now accepts whatever connect accepts, and errors from a bad call come from connect itself.
Common mistakes
- Expecting a list.
argsis a tuple, soargs.append(1)raisesAttributeError. Convert withlist(args)if you need to change it. - Duplicate names. If a named parameter already takes a keyword, it never reaches
**kwargs. Passing the same name twice, for examplef(1, a=2)withdef f(a, **kw), raisesTypeError: f() got multiple values for argument 'a'. - Silent typos. A function with
**kwargsaccepts misspelled keywords without complaint.describe(retires=2)just storesretires. Use explicit parameters when the set of options is known.
Exercise
What does this call print? def f(a, rest, key=0, *extra): return a, rest, key, extra print(f(1, 2, 3, key=4, flag=True))
Show answer
(1, (2, 3), 4, {'flag': True}). The value 1 binds to a, the extra positionals 2 and 3 form the tuple rest, key is keyword-only and receives 4, and the unmatched keyword flag goes into the extra dict.