Sub topic 9
Positional-only parameters with /
This chapter assumes you can define functions with default values, call them with keyword arguments, and read a TypeError traceback. It also assumes you know the * marker for keyword-only parameters. Positional-only parameters are the mirror image of those. They are written with / and need Python 3.8 or later.
What the slash does
A parameter is positional-only when it appears before a / in the parameter list. The caller must pass it by position. Passing it as name=value is an error.
def clamp(value, /, low=0, high=100):
return max(low, min(value, high))
print(clamp(150)) # 100
print(clamp(-5, high=10)) # 0
try:
clamp(value=5)
except TypeError as exc:
print(exc)The last call raises a TypeError whose message says positional-only arguments were passed as keyword arguments. Here value is positional-only, while low and high still accept either style.
The / is not a parameter. It is a marker that takes no argument, in the same way a bare * does.
The three kinds of parameter
A single signature can hold three regions, in this fixed order:
| Region | Written | How the caller may pass it |
|---|---|---|
| Positional-only | before `/` | by position only |
| Positional-or-keyword | between `/` and `*` (or with no markers at all) | by position or by keyword |
| Keyword-only | after `*` or after `*args` | by keyword only |
Ordinary parameters with no markers are positional-or-keyword, which is why most functions never need either marker.
A signature that uses all three regions looks like this:
def f(a, b, /, c, d=1, *, e, f=2):
return (a, b, c, d, e, f)
print(f(1, 2, 3, e=5)) # (1, 2, 3, 1, 5, 2)
print(f(1, 2, c=3, d=4, e=5)) # (1, 2, 3, 4, 5, 2)Rules the compiler enforces
- The
/may appear only once, and it must come before any*or*args. - The
/cannot be the first item. At least one parameter must precede it. - Within the positional regions, a parameter without a default cannot follow one with a default. This applies across the
/boundary too. - Keyword-only parameters are exempt from the last rule, because they are matched by name.
# Each of these definitions raises SyntaxError when compiled:
# def bad1(/, a): ... # nothing before the slash
# def bad2(a=1, b, /): ... # non-default after default
# def bad3(*, a, /): ... # slash after the starDefaults and positional-only parameters
Positional-only parameters may have defaults. The default is evaluated once at definition time, as with any other parameter. The practical limit is that you cannot skip an earlier one by naming a later one.
def span(start, stop=10, step=1, /):
return list(range(start, stop, step))
print(span(3)) # [3, 4, 5, 6, 7, 8, 9]
print(span(0, 10, 5)) # [0, 5]
# span(0, step=5) # TypeError: step is positional-onlyIf a caller commonly needs to set only step, this signature is a poor fit. Make step positional-or-keyword or keyword-only.
Why use it
The name is not part of the API
If callers can pass width=3, then width is a public name and renaming it breaks them. A positional-only parameter has no public name, so you can change it freely.
def area(width, height, /):
return width * height
# Later you rename the parameters. No caller can break.
def area(w, h, /):
return w * h
print(area(3, 4)) # 12Many built-ins work this way. len(obj=[1]) and divmod(x=7, y=2) both fail, and help(divmod) shows a / in its signature.
Names that clash with `**kwargs`
Without /, a named parameter and a **kwargs key cannot share a name. The keyword matches the parameter, not the dict.
def make_record(name, **fields):
return (name, fields)
try:
make_record("widget", name="blue")
except TypeError as exc:
print(exc) # make_record() got multiple values for argument 'name'Making name positional-only lets the same word appear in fields:
def make_record(name, /, **fields):
return (name, fields)
print(make_record("widget", name="blue")) # ('widget', {'name': 'blue'})The standard library uses this for self. A class that accepts arbitrary keyword entries can make self positional-only so that a caller may supply a key called self:
class Registry:
def __init__(self, /, **entries):
self.entries = entries
r = Registry(self="x", other=1)
print(r.entries) # {'self': 'x', 'other': 1}dict.update takes advantage of the same idea.
The argument has an obvious meaning
When a function takes one or two arguments and the name adds nothing, as in abs(x), min(a, b) or clamp(value), forcing a keyword only adds noise. A positional-only parameter documents that intent.
Reading a signature at runtime
inspect.signature shows the slash, and each parameter reports its kind.
import inspect
def f(a, b=2, /, c=3, *, d=4):
pass
sig = inspect.signature(f)
print(sig) # (a, b=2, /, c=3, *, d=4)
for p in sig.parameters.values():
print(p.name, p.kind.name)
# a POSITIONAL_ONLY
# b POSITIONAL_ONLY
# c POSITIONAL_OR_KEYWORD
# d KEYWORD_ONLY
print(f.__defaults__) # (2, 3)
print(f.__kwdefaults__) # {'d': 4}__defaults__ holds defaults for positional-only and positional-or-keyword parameters in one tuple. The tuple does not record where the slash was. Use inspect.signature when you need the kind.
Gotchas and failure modes
- Adding
/later is a breaking change. If any caller already usesvalue=5, makingvaluepositional-only breaks that call. Decide before you publish the function. - Removing
/later is safe. Turning a positional-only parameter into a positional-or-keyword one never breaks existing calls. This is the main reason to start strict. - Reordering still matters. Because callers pass by position, swapping
widthandheightsilently changes results when both are numbers. - Wrappers. A decorator written as
def wrapper(*args, **kwargs)forwards positional-only arguments correctly. A wrapper that declares the same names as keyword parameters does not, so keep wrappers generic. - Older Python. The syntax is a
SyntaxErrorbefore 3.8. Libraries that support older versions cannot use it.
Decision criteria
Choose each parameter's kind by asking what callers will gain from the name:
- Does the function take one or two arguments whose meaning is obvious from context? Use positional-only.
- Might you rename the parameter, or must it share a name with a
**kwargskey? Use positional-only. - Is the argument an optional setting such as
timeoutorssl? Use keyword-only. - Is it none of the above? Leave it positional-or-keyword.
Exercises
Exercise
Given def scale(x, factor=2, /): return x * factor, which of these calls raise a TypeError: scale(3), scale(3, 4), scale(3, factor=4), scale(x=3)?
Show answer
scale(3, factor=4) and scale(x=3) raise TypeError, because both parameters are positional-only and were passed by keyword. scale(3) returns 6 and scale(3, 4) returns 12.
Exercise
Write tag(name, /, **attrs) that returns a string like <a href="x"> for tag("a", href="x"). Explain why tag("a", name="n") works and what would happen without the /.
Show answer
Code: def tag(name, /, **attrs): return "<" + name + "".join(f' {k}="{v}"' for k, v in attrs.items()) + ">". With the slash, name="n" goes into attrs and gives <a name="n">. Without it, the keyword name would also bind the first parameter, and Python would raise TypeError: got multiple values for argument 'name'.
Exercise
For def f(a, b=2, /, c=3, *, d=4), what do f.__defaults__ and inspect.signature(f).parameters["b"].kind.name return?
Show answer
f.__defaults__ is (2, 3), covering both b and c. The kind of b is POSITIONAL_ONLY.