Sub topic 11
Controlling how callers pass arguments with / and *
This chapter assumes you can define functions with def, pass arguments by position and by keyword, and set default values. It also assumes you know what *args and **kwargs collect. Here you will use two markers in a parameter list, / and *, to decide which arguments callers must pass by position and which they must pass by name.
Why restrict how arguments are passed
By default, a parameter is positional-or-keyword. The caller can write power(2, 3) or power(base=2, exponent=3). That flexibility has a cost:
- Parameter names become part of your public interface. If you rename
exponenttoexp, every caller who used the keyword breaks. - Calls with several unlabeled values are hard to read. In
connect("example.com", 443, 5, False), the reader cannot tell what5orFalsemeans.
Python (3.8 and later) lets you tighten the rules with two markers in the parameter list:
| Marker | Effect on parameters near it | Caller must |
|---|---|---|
| `/` | Parameters **before** it are positional-only | Pass them by position |
| `*` | Parameters **after** it are keyword-only | Pass them by name |
| neither | Parameters are positional-or-keyword | Choose either style |
Keyword-only parameters with *
A bare * in a parameter list marks the end of the positional parameters. Everything after it must be passed by keyword.
def connect(host, port=8080, *, timeout=10, secure=True):
scheme = "https" if secure else "http"
return f"{scheme}://{host}:{port} (timeout={timeout}s)"
print(connect("example.com")) # https://example.com:8080 (timeout=10s)
print(connect("example.com", 443, timeout=5)) # https://example.com:443 (timeout=5s)
try:
connect("example.com", 443, 5)
except TypeError as error:
print("TypeError:", error)The last call fails with a TypeError because 5 would have to go into timeout, which accepts only a keyword. The exact wording of the message differs between Python versions.
Keyword-only parameters do not need a default value, even when they follow parameters that have one. That makes them a good way to require a value and force the caller to label it:
def resize(image, *, width, height):
return f"{image} resized to {width}x{height}"
print(resize("cat.png", width=640, height=480)) # cat.png resized to 640x480Calling resize("cat.png") raises a TypeError that lists the missing keyword-only arguments.
Keyword-only parameters after *args
If a function already has *args, that parameter takes the place of the bare *. Any parameter after it is keyword-only automatically.
def join_words(*words, sep=" "):
return sep.join(words)
print(join_words("a", "b", "c")) # a b c
print(join_words("a", "b", "c", sep="-")) # a-b-cHere sep can never be filled by position, because *words would swallow every positional value. Writing *words, * is a syntax error. You only need a bare * when there is no *args.
Positional-only parameters with /
A / marks the end of the positional-only parameters. Parameters before it cannot be passed by keyword.
def clamp(value, /, low=0, *, high=100):
return max(low, min(value, high))
print(clamp(150)) # 100
print(clamp(-5)) # 0
print(clamp(150, high=120)) # 120In this signature, value is positional-only, low accepts either style, and high is keyword-only. Calling clamp(value=150) raises a TypeError.
There are three reasons to use /:
- Free renaming. Nobody can depend on a name that cannot be used as a keyword. You can rename
valuetonumberlater without breaking any caller. - Meaningless names. For a function like
len(obj, /), a keyword adds nothing. Many built-in functions work this way. - Name collisions with `kwargs
.** A positional-only parameter does not claim its name, so a keyword with the same name can go into**kwargs`:
def make_record(name, /, **fields):
return name, fields
print(make_record("Ada", name="Lovelace", born=1815))
# ('Ada', {'name': 'Lovelace', 'born': 1815})Without the /, the call make_record("Ada", name="Lovelace") would fail with "got multiple values for argument 'name'".
Combining both markers
You can use both markers in one signature. The order is fixed:
The standard library's inspect module reports the kind of each parameter, which is a quick way to check a signature:
import inspect
def demo(a, b, /, c, d=0, *, e, f=1):
pass
for name, param in inspect.signature(demo).parameters.items():
print(name, param.kind.name)This prints:
a POSITIONAL_ONLY
b POSITIONAL_ONLY
c POSITIONAL_OR_KEYWORD
d POSITIONAL_OR_KEYWORD
e KEYWORD_ONLY
f KEYWORD_ONLYA realistic example puts the main value first, a convenient option in the middle, and a formatting flag at the end:
def format_price(amount, /, currency="USD", *, decimals=2):
return f"{amount:.{decimals}f} {currency}"
print(format_price(9.5)) # 9.50 USD
print(format_price(9.5, "EUR")) # 9.50 EUR
print(format_price(9.5, currency="EUR", decimals=3)) # 9.500 EURRules and common errors
The parser enforces the layout, so most mistakes show up as a SyntaxError when the file loads or a TypeError when the function is called.
| Mistake | What happens |
|---|---|
| `def f(a=1, b):` | `SyntaxError`: a parameter without a default cannot follow one with a default. This applies to positional parameters only. |
| `def f(*, a, b=1, c):` | Allowed. Keyword-only parameters are exempt from the default-ordering rule. |
| `def f(a, *):` | `SyntaxError`: a bare `*` must be followed by at least one named parameter. |
| `def f(*, a, /):` | `SyntaxError`: `/` must come before `*`. |
| `def f(a, /, /):` or `def f(*, a, *, b)` | `SyntaxError`: each marker can appear only once. |
| Passing a keyword-only value by position | `TypeError` at the call. |
| Passing a positional-only value by keyword | `TypeError` at the call. |
The defaults rule has a subtle effect on /. Positional-only parameters are still positional, so a required parameter cannot follow a defaulted one even across the slash. def f(a=1, /, b) is a SyntaxError.
Decision criteria
Use these rules of thumb when you design a signature:
- Use
*for options and flags. Boolean switches, timeouts, and counts are unclear without a label.connect(host, secure=False)is already clearer thanconnect(host, False), and keyword-only makes the clear form the only form. - Use
*when you expect to add parameters later. If every optional parameter is keyword-only, you can add new ones in any position without changing how existing callers pass arguments. - Use
/sparingly. It fits when the name is meaningless (len-style single arguments), when you want freedom to rename, or when you need to allow**kwargskeys that match a parameter name. - Do not use
/just to be strict. Callers lose the option of writingclamp(value=150), and for functions with several parameters, positional-only calls read worse. - Leave simple functions alone. For a function like
greet(name), extra markers add noise.
Exercises
Exercise
Write a function signature for send(message, recipient, retries, urgent) with these rules: message must be positional-only, recipient can be passed either way, and retries (default 3) and urgent (default False) must be passed by keyword. Then say which of these calls fail: send("hi", "bob"), send(message="hi", recipient="bob"), send("hi", "bob", 5).
Show answer
The signature is def send(message, /, recipient, *, retries=3, urgent=False):. The call send("hi", "bob") works. The call send(message="hi", recipient="bob") fails with a TypeError because message is positional-only. The call send("hi", "bob", 5) fails with a TypeError because retries is keyword-only and cannot take a third positional value.
Exercise
Why does def report(*items, title) force callers to write title= by name, and why is the signature def report(*items, *, title) invalid?
Show answer
*items collects every extra positional argument, so no positional value can ever reach title, which makes it keyword-only. Because *items already ends the positional parameters, a second bare * is redundant, and Python rejects a signature with more than one * in it.