Sub topic 8
Keyword-only parameters with *
This chapter assumes you can define and call functions, that you know default values and keyword arguments in calls, and that you can read a simple traceback. It covers how a bare * in a def line forces callers to pass some parameters by name, and when that is worth doing.
What a bare * does
A lone * in a parameter list is a marker, not a parameter. It takes no value. Every parameter written after it is keyword-only, so a 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", 6000)) # ('db.local', 6000, 10, True)
print(connect("db.local", timeout=5)) # ('db.local', 5432, 5, True)
print(connect("db.local", ssl=False, timeout=2)) # ('db.local', 5432, 2, False)host and port can be passed by position or by keyword. timeout and ssl can only be passed by keyword. Their order among themselves does not matter, because they are always named.
Here is what happens when a caller breaks the rule:
def connect(host, port=5432, *, timeout=10, ssl=True):
return (host, port, timeout, ssl)
try:
connect("db.local", 5432, 5)
except TypeError as exc:
print(exc)This prints connect() takes from 1 to 2 positional arguments but 3 were given. Python counts only the parameters before the * as positional slots. The third value has nowhere to go, so the call fails instead of silently setting timeout.
Where it fits in the binding order
Python fills parameters in a fixed sequence. It first assigns positional arguments to positional slots from left to right. It then matches keyword arguments by name. Last, it fills any remaining parameters from defaults, and raises an error if a required one is still empty.
The star changes only the first check. It sets how many positional slots exist. Everything after that step works as it does for ordinary parameters.
Keyword-only parameters without defaults
Keyword-only parameters do not need defaults. This is a difference from ordinary parameters. Normally a parameter without a default cannot follow one with a default. After the * that rule does not apply, because the parameters are matched by name and not by position.
def resize(image, *, width, height, keep_ratio=False):
return f"{image}: {width}x{height} keep_ratio={keep_ratio}"
print(resize("cat.png", width=64, height=32))
try:
resize("cat.png", width=64)
except TypeError as exc:
print(exc)
try:
resize("cat.png", 64, 32)
except TypeError as exc:
print(exc)The output is:
cat.png: 64x32 keep_ratio=False
resize() missing 1 required keyword-only argument: 'height'
resize() takes 1 positional argument but 3 were givenThis gives you a required argument that callers must spell out. resize("cat.png", 64, 32) hides which number is the width. resize("cat.png", width=64, height=32) does not. The error for a missing value names the parameter, which makes the fix obvious.
The two ways to write the marker
You can start the keyword-only section in two ways.
| Form | Example | Extra positionals |
|---|---|---|
| Bare `*` | `def f(a, *, b)` | Rejected with a `TypeError` |
| `*args` | `def f(a, *args, b)` | Collected into the tuple `args` |
A *args parameter does the same marking job as a bare *. Anything after it is keyword-only. You do not write both, since a signature has only one star-section.
def join_all(*parts, sep=" "):
return sep.join(parts)
print(join_all("a", "b", "c")) # a b c
print(join_all("a", "b", "c", sep="-")) # a-b-cHere sep must be keyword-only. Without that, join_all("a", "b", "-") would treat "-" as one more part. Any function that accepts an open-ended list of positional values and also has options needs this form. This is the same reason print(*objects, sep=" ", end="\n") is shaped the way it is.
Syntax rules and mistakes
Python rejects a few signatures when it compiles the def:
def f(*):is aSyntaxError, because a bare*must be followed by at least one named parameter.def f(*, **kwargs):is also aSyntaxError, because**kwargsis not a named keyword-only parameter.def f(**kwargs, *, a):is aSyntaxError, because nothing may follow**kwargs.
A valid signature can combine all the parts in this order: ordinary parameters, the star section, keyword-only parameters, then **kwargs.
def log(message, level="info", *, stream=None, **extra):
return (message, level, stream, extra)
print(log("started", stream="stdout", user="ada"))
# ('started', 'info', 'stdout', {'user': 'ada'})The name user is not a declared parameter, so it lands in extra. The name stream is declared, so it binds there and never reaches extra.
A common slip is a misspelled keyword. With a keyword-only parameter and no **kwargs, Python reports it directly:
def connect(host, *, timeout=10):
return (host, timeout)
try:
connect("db.local", timeot=5)
except TypeError as exc:
print(exc)This prints connect() got an unexpected keyword argument 'timeot'. If the function had a **kwargs, the typo would be swallowed without any error. For that reason, add **kwargs only when you mean to accept arbitrary names.
Passing keyword-only arguments from a dict
Unpacking a mapping with ** supplies keyword arguments, so it works with keyword-only parameters. This is the usual way to pass stored options.
def connect(host, port=5432, *, timeout=10, ssl=True):
return (host, port, timeout, ssl)
options = {"timeout": 5, "ssl": False}
print(connect("db.local", **options)) # ('db.local', 5432, 5, False)Unpacking a sequence with * can never reach a keyword-only parameter. It only fills positional slots.
Defaults still follow the usual rules
Keyword-only defaults are evaluated once, when the def runs, exactly like other defaults. The mutable default pitfall applies to them too:
def collect(value, *, bucket=[]): # same bug as before
bucket.append(value)
return bucket
print(collect(1)) # [1]
print(collect(2)) # [1, 2]Use the None sentinel here as well: bucket=None, then if bucket is None: bucket = [] in the body.
Inspecting what you defined
Defaults of keyword-only parameters are stored apart from the positional ones. They live in __kwdefaults__, a dict, while positional defaults live in the tuple __defaults__. A required keyword-only parameter has no entry in either.
import inspect
def f(a, b=2, *, c, d=4):
pass
print(f.__defaults__) # (2,)
print(f.__kwdefaults__) # {'d': 4}
print(inspect.signature(f)) # (a, b=2, *, c, d=4)
for name, p in inspect.signature(f).parameters.items():
print(name, p.kind.name)The loop prints a POSITIONAL_OR_KEYWORD, b POSITIONAL_OR_KEYWORD, c KEYWORD_ONLY, d KEYWORD_ONLY. The kind attribute is the reliable way for tools and decorators to find which parameters must be named. The signature string keeps the * visible.
When to use keyword-only parameters
Use them when the call site would otherwise be unclear or fragile.
- Boolean and flag options.
export(data, True, False)is unreadable.export(data, header=True, append=False)is clear. - Several parameters of the same type. Two or three numbers or strings in a row are easy to swap by position.
- Options that may grow. If callers must name an option, you can add new options or reorder them later without breaking existing calls. Positional parameters tie callers to their order.
- Parameters after
*args. There is no other way to give them values.
Keep the core inputs positional. A function like connect(host, *, timeout=10) reads well. A function that forces connect(host="db.local") for its single obvious input is just noisy.
Making an existing positional parameter keyword-only is a breaking change. Every caller that passed it by position now fails with a TypeError. Add the * when you first design the function, or plan for a deprecation period.
Exercises
Exercise
Given def export(rows, path, *, header=True, append=False): ..., which of these calls raise a TypeError, and why? (a) export(r, "out.csv") (b) export(r, "out.csv", False) (c) export(r, "out.csv", append=True) (d) export(r, path="out.csv", header=False)
Show answer
Only (b) raises a TypeError. The third positional value has no slot, because only rows and path come before the *, so Python reports that the function takes 2 positional arguments but 3 were given. Calls (a), (c) and (d) are valid. Call (d) passes path by keyword, which is allowed because path is an ordinary parameter.
Exercise
Write a function scale(*numbers, factor) that returns a list of each number multiplied by factor, with factor required. What does scale(1, 2, 3) do, and what does scale(1, 2, factor=10) return?
Show answer
Definition: def scale(*numbers, factor): return [n * factor for n in numbers]. The call scale(1, 2, 3) raises TypeError: scale() missing 1 required keyword-only argument: 'factor', because all three values are collected into numbers. The call scale(1, 2, factor=10) returns [10, 20].
Exercise
For def f(a, *, b, c=3): pass, what do f.__defaults__ and f.__kwdefaults__ contain?
Show answer
f.__defaults__ is None, because there are no defaults on positional-capable parameters. f.__kwdefaults__ is {'c': 3}. The required keyword-only parameter b has no default, so it appears in neither.