Sub topic 8
Keyword-only parameters with *
This chapter assumes you can define and call functions, read a simple traceback, and know that default values are evaluated once at definition time. Here you will see how a bare * in a parameter list forces callers to name certain arguments.
The problem: long positional tails
Suppose a function takes a required host and several optional settings. Callers can pass the settings by position, and call sites become hard to read:
def connect(host, port=5432, timeout=10, ssl=True):
return (host, port, timeout, ssl)
print(connect("db.local", 5432, 5, False))A reader cannot tell what 5 or False means without looking up the definition. If a later version inserts a new parameter before timeout, this call silently changes meaning.
The bare `*` marker
A lone * in the parameter list means "no more positional arguments after this point." Every parameter after it is keyword-only. The caller must pass it as name=value.
def connect(host, port=5432, *, timeout=10, ssl=True):
return (host, port, timeout, ssl)
print(connect("db.local")) # ('db.local', 5432, 10, True)
print(connect("db.local", timeout=5)) # ('db.local', 5432, 5, True)
print(connect("db.local", 6000, ssl=False)) # ('db.local', 6000, 10, False)The * is not a parameter itself. It takes no value and does not collect anything. It only marks a boundary.
What happens when you break the rule
Passing a keyword-only parameter by position raises a TypeError. Python counts the positional arguments it can accept and reports the excess.
def connect(host, port=5432, *, timeout=10, ssl=True):
return (host, port, timeout, ssl)
try:
connect("db.local", 5432, 5)
except TypeError as e:
print(e)
# connect() takes from 1 to 2 positional arguments but 3 were givenThe message mentions positional arguments, not timeout. When you see "takes from N to M positional arguments but K were given" and the function has a *, check whether you meant to pass a value by keyword.
Keyword-only parameters without defaults
A keyword-only parameter does not need a default. If it has none, the caller must supply it. This is the one place where a parameter without a default may follow one that has a default.
def send(message, retries=3, *, channel):
return (message, retries, channel)
print(send("hi", channel="ops")) # ('hi', 3, 'ops')
try:
send("hi")
except TypeError as e:
print(e)
# send() missing 1 required keyword-only argument: 'channel'Without the *, def send(message, retries=3, channel) is a SyntaxError, because a non-default parameter cannot follow a default one. The keyword-only section is exempt because its parameters are never matched by position, so there is no ambiguity.
Combining with `*args`
If a function already has *args, that parameter also ends the positional section. Anything after it is keyword-only, and you do not add a second bare *.
def log(level, *messages, sep=" ", end="\n"):
print(level + ":", sep.join(messages), end=end)
log("INFO", "started", "ok") # INFO: started ok
log("INFO", "a", "b", sep="-") # INFO: a-bHere sep and end can never be filled by position, because *messages takes all extra positional values.
Why use it
- Call sites document themselves:
timeout=5is clearer than5. - You can reorder or add keyword-only parameters later without breaking callers.
- Boolean flags and tuning options are easy to confuse by position. Forcing names prevents mistakes such as swapping
sslandtimeout.
Use it for options that are secondary to the function's main purpose. Leave the one or two essential inputs as ordinary parameters.
Exercise
Given def resize(image, width, height, *, keep_ratio=True, resample="linear"), which of these calls raises a TypeError, and why? (a) resize(img, 100, 50) (b) resize(img, 100, 50, False) (c) resize(img, 100, 50, resample="nearest")
Show answer
Only (b) raises a TypeError. The fourth value False would have to bind to keep_ratio, but keep_ratio is keyword-only, so the function accepts only three positional arguments. Calls (a) and (c) are valid: (a) uses both defaults, and (c) passes resample by keyword.
Exercise
Rewrite def export(data, path, overwrite=False, compress=True) so that overwrite and compress must be passed by keyword. What happens to existing callers that pass them by position?
Show answer
def export(data, path, *, overwrite=False, compress=True). Existing callers that pass overwrite or compress by position now raise a TypeError ("takes 2 positional arguments but 3 were given"), so they must be updated to use overwrite=... and compress=....