Who Decides How a Function Is Called? Positional-Only and Keyword-Only Parameters in Python
This article explains how the markers * and / make Python parameters keyword-only or positional-only, which errors they prevent, and which signature changes stay compatible.
The parameters of a Python function accept, by default, both styles of call: a value may be passed by position or by name. The present article examines the two markers that restrict this freedom, *, which makes the following parameters keyword-only (PEP 3102, Python 3.0), and /, which makes the preceding parameters positional-only (PEP 570, Python 3.8). It explains which errors each marker prevents, how they combine in a single signature, how they interact with *args and **kwargs, and which changes to a signature remain compatible with existing callers. Deciding in the signature itself how a function may be called, so that the interpreter enforces the decision on every call, is the secret weapon of these two markers.
Positional-or-Keyword: The Default
A parameter declared without markers is positional-or-keyword: the caller may pass its value in order or by name, and both calls below are equivalent.
def make_greeting(name, message):
return f"{message}, {name}"
print(make_greeting("Maria", "Good morning")) # Output: Good morning, Maria
print(make_greeting(message="Hello", name="Leo")) # Output: Hello, Leo
def send_notification(recipient, title, message):
return f"Sending {title!r} to {recipient}"
print(send_notification("New user signup", "[email protected]", "A user joined."))
# Output: Sending '[email protected]' to New user signup
The flexibility has a cost when several parameters have the same type: the last call swaps the recipient and the title, and the function runs without any error because three strings satisfy any order. Nothing in the call reveals the mistake, which is precisely the kind of error that a keyword-only signature makes impossible.
Keyword-Only Parameters with *
Every parameter that follows a bare * in the signature must be passed by name. The marker originated in PEP 3102 for functions that accept a variable number of positional arguments, *args, together with options, and a bare * applies the same rule without accepting extra positional values.
def send_notification(*, recipient, title, message):
return f"Sending {title!r} to {recipient}"
print(send_notification(recipient="[email protected]", title="New user signup", message="A user joined."))
# Output: Sending 'New user signup' to [email protected]
try:
send_notification("[email protected]", "New user signup", "A user joined.")
except TypeError as error:
print(error) # Output (CPython 3.12): send_notification() takes 0 positional arguments but 3 were given
def log(*parts, sep=" ", level):
return f"[{level}] " + sep.join(parts)
print(log("disk", "full", level="WARN")) # Output: [WARN] disk full
The positional call is now rejected, and the valid call documents the meaning of each value at the call site. The function log shows the original use case: after *parts, any further parameter can only be reached by name, because every positional value is absorbed by the tuple. It also shows that a keyword-only parameter without a default, level, may follow one with a default, an order that is not allowed among ordinary parameters.
Positional-Only Parameters with /
Every parameter that precedes / must be passed by position, and its name becomes an internal detail of the function. Many built-in functions have behaved this way for years: inspect.signature(len) returns (obj, /), and a call such as len(obj="hello") raises TypeError; PEP 570 gave Python code the same capability. In the words of a certain armoured bounty hunter, "This is the way", and the standard library follows it consistently.
import math
def distance(x, y, /):
return math.hypot(x, y)
print(distance(3, 4)) # Output: 5.0
try:
distance(x=3, y=4)
except TypeError as error:
print(error) # Output (CPython 3.12): distance() got some positional-only arguments passed as keyword arguments: 'x, y'
def tag(name, /, **attributes):
return name, attributes
print(tag("a", name="link")) # Output: ('a', {'name': 'link'})
def tag_unsafe(name, **attributes):
return name, attributes
try:
tag_unsafe("a", name="link")
except TypeError as error:
print(error) # Output (CPython 3.12): tag_unsafe() got multiple values for argument 'name'
Since no caller can use the names x and y, the author of distance may rename them later without breaking any code, which is the main argument of PEP 570 for library APIs. The second pair of functions shows a less evident benefit: when a function also accepts arbitrary keywords, a positional-only parameter leaves its name free for the caller, so tag receives name="link" as an attribute, whereas tag_unsafe rejects the call because the keyword collides with its own parameter. The constructor dict and the method dict.update rely on the same rule.
Combining Both Markers
A signature may contain both markers, in this order, which divides its parameters into three groups whose kinds the module inspect reports directly.
import inspect
def create_post(author_id, /, category="general", *, title, content):
return f"{author_id} | {category} | {title}"
print(create_post(101, "python", title="Parameters", content="..."))
# Output: 101 | python | Parameters
print(create_post(101, category="python", title="Parameters", content="..."))
# Output: 101 | python | Parameters
kinds = [p.kind.name for p in inspect.signature(create_post).parameters.values()]
print(kinds) # Output: ['POSITIONAL_ONLY', 'POSITIONAL_OR_KEYWORD', 'KEYWORD_ONLY', 'KEYWORD_ONLY']
Parameters before / are positional-only, parameters between / and * keep the default behaviour, and parameters after * are keyword-only. The same classification is what inspect.signature exposes to frameworks and documentation tools, as described in the article devoted to the inspect module, and data classes generate keyword-only parameters in their constructor with the option kw_only, examined in the article devoted to data classes.
Pitfalls of Restricted Parameters
The markers fix part of the public contract of a function, so they must be chosen with the same care as the names of the function and its parameters. Six pitfalls are distinguished, which are the following:
- Adding a marker to an existing API. Placing
/before a parameter that callers already pass by name, or*before one that they pass by position, breaks those callers. - Adding a required keyword-only parameter. A new keyword-only parameter is compatible only if it has a default; otherwise every existing call fails.
- Positional-only names in documentation. The names before
/still appear inhelp()and in signatures, so they should remain descriptive even though callers cannot use them. - Confusing a bare
*with*args. A bare*rejects extra positional values, whereas*argscollects them; a signature that ends with a bare*and no parameter after it is a syntax error. - Wrappers that hide the signature. A decorator that defines
wrapper(*args, **kwargs)withoutfunctools.wrapsmakes the markers invisible toinspect.signatureand to the reader, although the inner function still enforces them. - Overusing positional-only parameters. A function with several positional-only parameters of the same type reintroduces the swapping problem that keyword-only parameters solve.
The second pitfall is reproduced in the following example.
def send_notification(*, recipient, title, priority):
return recipient, title, priority
try:
send_notification(recipient="[email protected]", title="Signup")
except TypeError as error:
print(error) # Output (CPython 3.12): send_notification() missing 1 required keyword-only argument: 'priority'
def send_notification(*, recipient, title, priority="normal"):
return recipient, title, priority
print(send_notification(recipient="[email protected]", title="Signup"))
# Output: ('[email protected]', 'Signup', 'normal')
The first version represents a function to which a required parameter was added, and every call written for the earlier signature fails. With a default value, the new parameter is invisible to existing callers, and since keyword-only parameters are matched by name, their order in the signature may also change without consequence.
Choosing a Parameter Kind
Consequently, the choice depends on whether the name of a parameter carries meaning for the caller, as the official tutorial recommends and the following table summarizes.
| Situation | Recommended approach |
|---|---|
The name has no meaning for the caller, as in distance(x, y) |
Positional-only, with / |
| The function also accepts arbitrary keywords | Positional-only for its own parameters |
| Several parameters of the same type, or boolean flags | Keyword-only, with * |
| Options that follow a variable number of positional values | Keyword-only parameters after *args |
| A library function whose parameter names may change | Positional-only |
| A short internal function | The default, without markers |
Conclusion
It is concluded that the markers * and / move a decision from the documentation into the signature: * forces the caller to name the values whose meaning would otherwise be ambiguous, and / frees the function to rename parameters and to accept arbitrary keywords without collisions. This magic is enforced by the interpreter on every call and reported by inspect.signature, which makes it part of the contract of an API, and it demands the same care as any contract when the signature evolves. Functions with many keyword-only options are often an alternative to classes that build an object step by step, the Builder pattern, which is developed in a future article of this series.