Sub topic 7
Keyword-only and Positional-Only Parameters
The previous chapters covered how *args and **kwargs collect extra arguments and how parameters must be ordered. This chapter covers two markers that restrict how a caller may supply a value. A parameter after * can only be passed by name, and a parameter before / can only be passed by position.
This chapter assumes you can define and call functions, know positional and keyword arguments and default values, and have read the earlier chapters on *args, **kwargs and parameter order. Positional-only syntax needs Python 3.8 or later. The examples were written for Python 3.8+.
Three ways to receive a value
Every named parameter in a signature has one of three binding rules. The rule decides whether a caller may use a position, a name, or either.
| Kind | Where it appears | Caller may pass by position | Caller may pass by name |
|---|---|---|---|
| Positional-only | Before `/` | Yes | No |
| Positional or keyword | Between `/` and `*` (or with no markers at all) | Yes | Yes |
| Keyword-only | After `*` or after `*args` | No | Yes |
Most parameters you have written so far are "positional or keyword". That is the default, and it is also the most permissive. It lets callers use whichever form they like, which means both forms become part of your function's public contract.
Keyword-only parameters
A keyword-only parameter must be passed by name. You create one in either of two ways:
- Put it after
*args. Every extra positional argument is consumed by*args, so nothing positional can reach the later parameters. - Put it after a bare
*. The bare star collects nothing. It only marks the point where keyword-only parameters start.
Here is the bare-star form:
def connect(host, port=80, *, timeout=10, retries=3):
return host, port, timeout, retries
print(connect("example.com", 443, timeout=5))
# ('example.com', 443, 5, 3)
try:
connect("example.com", 443, 5)
except TypeError:
print("TypeError: timeout must be passed by name")The third positional value 5 has nowhere to go, because host and port are already filled and no *args exists to absorb it. Python raises a TypeError.
The *args form works the same way. The built-in print has this shape: print(*objects, sep=' ', end='\n', ...). You can write your own version:
def join_words(*words, sep=" ", end=""):
return sep.join(words) + end
print(join_words("a", "b", "c")) # a b c
print(join_words("a", "b", "c", sep="-")) # a-b-cA call such as join_words("a", "b", "-") would treat "-" as another word. Because sep sits after *words, it cannot be set by accident.
Required keyword-only parameters
Keyword-only parameters may or may not have defaults. Unlike ordinary parameters, a required keyword-only parameter can follow one that has a default:
def resize(image, *, width=None, height):
return image, width, height
print(resize("cat.png", height=100))
# ('cat.png', None, 100)
try:
resize("cat.png")
except TypeError as error:
print(error)
# resize() missing 1 required keyword-only argument: 'height'For ordinary parameters, def f(a=1, b) is a SyntaxError, because Python could not tell which argument a single positional value belongs to. Keyword-only parameters are matched by name, so that ambiguity does not exist and the ordering restriction does not apply.
Why use keyword-only parameters
- Readable calls.
fetch(url, True, False, 3)tells the reader nothing.fetch(url, verify=True, stream=False, retries=3)is self-explanatory. - Safe growth. You can add a new keyword-only parameter with a default without breaking any existing call. You can also reorder keyword-only parameters freely, since no caller depends on their position.
- Protection from swapped values. Several boolean or numeric options in a row are easy to transpose by position. Names remove that risk.
A good rule of thumb: required, obvious inputs stay positional. Options, flags and tuning values become keyword-only.
Positional-only parameters
A / in the signature makes every parameter before it positional-only. The caller cannot use the parameter's name.
def clamp(value, low, high, /):
return max(low, min(value, high))
print(clamp(15, 0, 10)) # 10
try:
clamp(value=15, low=0, high=10)
except TypeError:
print("TypeError: names are not accepted")Many built-ins already work this way. len(obj, /) accepts no obj= keyword. help(len) and inspect.signature show the / marker.
Why use positional-only parameters
- Free renaming. If callers can never write
clamp(value=15, ...), you can renamevaluetonumberlater without breaking anyone. - Names that carry no meaning. For
len(x)orabs(x), a parameter name adds nothing. Making it positional-only keeps the name out of the public API. - Freeing names for `kwargs`.** This is the most practical reason, and the next section covers it.
Positional-only parameters and `**kwargs`
Suppose a function takes a first argument and also wants to accept arbitrary keyword fields. If a caller uses the same name as the first parameter, an ordinary signature fails:
def make_record(name, **fields):
return name, fields
try:
make_record("Ada", name="override")
except TypeError as error:
print(error)
# make_record() got multiple values for argument 'name'Marking name positional-only removes the conflict. The keyword name= no longer refers to the first parameter, so it falls into **fields:
def make_record(name, /, **fields):
return name, fields
print(make_record("Ada", name="override", age=36))
# ('Ada', {'name': 'override', 'age': 36})This is why dict.update and similar methods take self as positional-only. A dictionary can have a key named "self", and d.update(self=1) has to work.
Combining all the markers
You can use /, * and **kwargs together. The full left-to-right order, from the earlier chapter on parameter order, is:
- Positional-only parameters, then
/. - Positional-or-keyword parameters, with or without defaults.
*argsor a bare*.- Keyword-only parameters.
**kwargs.
def g(a, /, b, *, c):
return a, b, c
print(g(1, 2, c=3)) # (1, 2, 3)
print(g(1, b=2, c=3)) # (1, 2, 3)Here a must be positional, b may be either, and c must be named. Two calls fail:
def g(a, /, b, *, c):
return a, b, c
for call in (lambda: g(a=1, b=2, c=3), lambda: g(1, 2, 3)):
try:
call()
except TypeError as error:
print("TypeError")
# TypeError
# TypeErrorThe first call names a, which is positional-only. The second call passes 3 positionally, but c is keyword-only.
A fuller example uses every zone, including defaults and **kwargs:
def request(method, url, /, params=None, *, timeout=10, **headers):
return method, url, params, timeout, headers
print(request("GET", "/items", {"page": 2}, timeout=3, Accept="text/json"))
# ('GET', '/items', {'page': 2}, 3, {'Accept': 'text/json'})Defaults follow the usual rule within the positional region. Once a parameter has a default, every later positional-only or positional-or-keyword parameter must also have one. A default on a positional-only parameter is legal:
def power(base, exponent=2, /):
return base ** exponent
print(power(5)) # 25
print(power(2, 10)) # 1024Syntax rules and errors at definition time
Python checks the markers when it compiles the function. These definitions are all SyntaxError:
| Definition | Problem |
|---|---|
| `def f(/, a)` | Nothing precedes the `/` |
| `def f(a, /, b, /)` | Two `/` markers |
| `def f(*, **kwargs)` | Bare `*` with no keyword-only parameter after it |
| `def f(*args, *, b)` | Two `*` markers |
| `def f(**kwargs, b)` | Nothing may follow `**kwargs` |
| `def f(a=1, /, b)` | A parameter without a default follows one with a default |
| `def f(*, a, /)` | `/` must come before `*` |
The last two rows deserve attention. The default-value rule still applies across the / boundary. A call-time error is also possible. When a required keyword-only parameter is missing, you get the "missing 1 required keyword-only argument" message shown earlier.
Inspecting the kinds at runtime
The inspect module reports each parameter's kind. This is useful when you write decorators or tools that need to understand a signature.
import inspect
def g(a, /, b, *args, c, **kwargs):
pass
print(inspect.signature(g))
# (a, /, b, *args, c, **kwargs)
for param in inspect.signature(g).parameters.values():
print(param.name, param.kind.name)
# a POSITIONAL_ONLY
# b POSITIONAL_OR_KEYWORD
# args VAR_POSITIONAL
# c KEYWORD_ONLY
# kwargs VAR_KEYWORDThe five kind names are POSITIONAL_ONLY, POSITIONAL_OR_KEYWORD, VAR_POSITIONAL, KEYWORD_ONLY and VAR_KEYWORD. They correspond exactly to the zones in the diagram above.
Interaction with unpacking and wrappers
Call-site unpacking respects these restrictions. A dictionary unpacked with ** supplies keywords, so it cannot fill a positional-only parameter:
def area(width, height, /):
return width * height
print(area(*(3, 4))) # 12
try:
area(**{"width": 3, "height": 4})
except TypeError:
print("TypeError: positional-only parameters cannot be set by keyword")A wrapper that forwards *args, **kwargs keeps the original call shape. If the caller passes 3, 4 positionally, the wrapped function receives 3, 4 positionally. The wrapper does not need to know which parameters are positional-only or keyword-only.
If you build a wrapper with a specific signature instead, copy the markers you care about. A wrapper declared as def wrapper(width, height) would accept wrapper(width=1, height=2), even though the wrapped function rejects the keywords when the wrapper forwards them as keywords. Forwarding *args, **kwargs avoids this mismatch.
Common mistakes
- Expecting a bare
*to collect values. It does not.def f(a, *, b)still rejects a second positional argument. The callf(1, 2)raisesTypeError. - Putting keyword-only parameters before the star. Only parameters after
*or*argsare keyword-only. A parameter before them can still be passed by position. - Making a public parameter positional-only too early. You can later relax a positional-only parameter into an ordinary one without breaking callers. You cannot go the other way. Making an existing parameter positional-only breaks every caller that used its name.
- Forgetting that
/needs Python 3.8. On older versions the signature is aSyntaxError. Check your minimum supported version before adopting it. - Using `kwargs
where a keyword-only parameter would do.** If you know the option names in advance, list them as keyword-only parameters. Typos then fail loudly (unexpected keyword argument`) instead of being silently collected.
Choosing between the forms
| Situation | Prefer |
|---|---|
| Option flag or tuning value, such as `verbose`, `timeout`, `retries` | Keyword-only |
| Single obvious input with a name that adds nothing, such as `len(obj)` | Positional-only |
| Function takes both a first argument and open-ended `**kwargs` | Positional-only for the first argument |
| Two or three clear, required inputs, such as `area(width, height)` | Ordinary (positional or keyword) |
| Several similar values that could be swapped, such as `copy(src, dst)` | Ordinary, or keyword-only for the second |
Exercise
What does each of these calls do with the function below? Say whether it succeeds, and give the returned tuple if it does. def h(x, /, y, *, z=0): return x, y, z 1. h(1, 2) 2. h(1, y=2, z=3) 3. h(x=1, y=2) 4. h(1, 2, 3)
Show answer
1. Succeeds and returns (1, 2, 0). z uses its default. 2. Succeeds and returns (1, 2, 3). y may be given by name and z must be. 3. Raises TypeError, because x is positional-only and cannot be passed by name. 4. Raises TypeError, because the third positional value has no place to go and z is keyword-only.
Exercise
Write a function log(message, /, *, level="info", **context) that returns a string of the form "LEVEL: message" followed by the context entries as key=value pairs separated by spaces. Then explain why message is positional-only and show that the call log("hi", message="x", level="warn") works.
Show answer
One solution: def log(message, /, , level="info", context): parts = [f"{level.upper()}: {message}"] parts += [f"{key}={value}" for key, value in context.items()] return " ".join(parts) print(log("hi", message="x", level="warn")) # WARN: hi message=x message is positional-only, so the keyword message="x" does not collide with it. It is collected into *context instead. level is keyword-only, so it cannot be set by accident through an extra positional argument.
Exercise
Which of these definitions are valid, and why are the others rejected? (a) def f(a, , b): (b) def f(, a=1, b): (c) def f(a=1, b): (d) def f(a, /, ): (e) def f(, **kw):
Show answer
(a) is valid. (b) is valid, because a required keyword-only parameter may follow a defaulted one. (c) is a SyntaxError, because a parameter without a default follows one with a default among ordinary parameters. (d) is a SyntaxError, because a bare must be followed by at least one keyword-only parameter. (e) is a SyntaxError for the same reason: the bare has no keyword-only parameter after it.