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 simple TypeError traceback. It also assumes you know the * marker for keyword-only parameters from the previous chapter.
What the slash does
A bare / in a parameter list marks the end of the positional-only parameters. Every parameter before it must be passed by position. The caller cannot name it.
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 error:
print(error)The last call fails with a message like clamp() got some positional-only arguments passed as keyword arguments: 'value'. Parameters after the slash, here low and high, still accept either style.
Python 3.8 added this syntax. Many built-ins already worked this way. help(divmod) shows divmod(x, y, /), and len(obj=[1, 2]) raises a TypeError.
Ordering with / and *
The slash and the star can appear in the same signature. The order is fixed:
- Positional-only parameters, then
/. - Positional-or-keyword parameters.
*or*args, then keyword-only parameters.**kwargs.
def request(url, /, method="GET", *, timeout=10):
return (url, method, timeout)
print(request("http://x.test")) # ('http://x.test', 'GET', 10)
print(request("http://x.test", "POST")) # ('http://x.test', 'POST', 10)
print(request("http://x.test", timeout=3)) # ('http://x.test', 'GET', 3)Defaults follow the usual rule. Once a positional parameter has a default, every positional parameter after it needs one too, and this includes parameters on either side of the slash. Keyword-only parameters are exempt from that rule.
Why use positional-only parameters
There are three practical reasons.
- The name is not part of the API. A parameter named
valueorxcarries no meaning for callers. If it is positional-only, you can rename it later without breaking anyone's code. - The name is free for other uses. Positional-only names do not collide with keys in
**kwargs, as shown below. - Some parameters are obvious by position. In
clamp(value)ordivmod(x, y), a keyword adds nothing.
def update(record, /, **fields):
record.update(fields)
return record
print(update({"id": 1}, record="draft")) # {'id': 1, 'record': 'draft'}Without the slash, record="draft" would raise TypeError because record would be passed twice. With it, the keyword goes into fields.
Inspecting the result
inspect.signature prints the slash, so you can check how a function, including a built-in, accepts its arguments.
import inspect
def clamp(value, /, low=0, high=100):
return max(low, min(value, high))
print(inspect.signature(clamp)) # (value, /, low=0, high=100)
print(inspect.signature(divmod)) # (x, y, /)Common mistakes
- Putting
/after a keyword-only marker, or after*args. This is aSyntaxError, because the slash must come first. - Using two slashes, or a slash as the first item in the list (
def f(/, a)). Both areSyntaxError. - Passing a positional-only parameter by keyword and expecting a default to fill in. Python reports the keyword as invalid and does not substitute a default.
Exercise
Given def area(width, height, /, unit="cm"): return f"{width * height} {unit}2", which of these calls raise a TypeError: area(2, 3), area(2, height=3), area(2, 3, unit="m"), area(2, 3, "m")? Why?
Show answer
Only area(2, height=3) raises a TypeError. height sits before the slash, so it must be passed by position. The other calls pass width and height by position, and unit may be given either by keyword or by position.
Exercise
Write a function first_word(text, /, *, sep=" ") that returns the part of text before the first separator. Which arguments can a caller pass by keyword?
Show answer
def first_word(text, /, *, sep=" "):
return text.split(sep)[0]
Only sep can be passed by keyword, and it must be. text must be passed by position.