Sub topic 7
Keyword-only and positional-only parameters
This chapter assumes you can define functions with default values, and that you know *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary. It also assumes you know the standard parameter order from the previous chapter. Here you will learn two markers, * and /, that control how callers may pass each argument.
Why restrict how arguments are passed?
By default, a parameter such as b in def f(a, b) accepts a value either by position (f(1, 2)) or by name (f(a=1, b=2)). That flexibility has costs:
- A function with many options can be called as
connect("db", 5, 3, True), and nobody can tell what5or3means. - If callers use a parameter name, renaming it breaks their code.
Python provides two markers to narrow how a parameter can be passed.
Keyword-only parameters
Any parameter that comes after *args, or after a bare *, is keyword-only. A caller must pass it by name.
def connect(host, *, timeout=10, retries=3):
return f"{host} timeout={timeout} retries={retries}"
print(connect("db.local")) # db.local timeout=10 retries=3
print(connect("db.local", timeout=30)) # db.local timeout=30 retries=3
try:
connect("db.local", 30)
except TypeError as error:
print(error) # connect() takes 1 positional argument but 2 were givenThe bare * collects nothing. It only marks where positional parameters end. If the function already has *args, you don't need a bare *, because *args does the same job:
def join(*parts, sep="-"):
return sep.join(parts)
print(join("a", "b", "c")) # a-b-c
print(join("a", "b", "c", sep="/")) # a/b/cThis is the only way to give a parameter a default after *args that callers can actually override. A value passed positionally would be swallowed by *args, so sep can only be set by name.
Keyword-only parameters may be required, as in def f(*, c). A required keyword-only parameter does not need a default, and it may come after one that has a default.
Positional-only parameters
A / in the signature makes every parameter before it positional-only. Callers cannot name them.
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)
try:
g(a=1, b=2, c=3)
except TypeError as error:
print(error) # g() got some positional-only arguments passed as keyword arguments: 'a'
try:
g(1, 2, 3)
except TypeError as error:
print(error) # g() takes 2 positional arguments but 3 were givenThe function g has three zones, separated by the two markers:
Common reasons to use /:
- The name carries no meaning, as with
len(obj). Many built-in functions work this way. - You want freedom to rename the parameter later without breaking callers.
- You want
**kwargsto accept a key that matches a parameter name.
The last reason is a real gotcha. Without /, this fails:
def update(self, **kwargs):
return kwargs
try:
update(1, self=2)
except TypeError as error:
print(error) # update() got multiple values for argument 'self'With /, the name self is free for use as a keyword:
def update(self, /, **kwargs):
return self, kwargs
print(update(1, self=2)) # (1, {'self': 2})The first self is filled by position. The keyword self=2 is not matched to the positional-only parameter, so it falls into kwargs.
Defaults and ordering rules
Rules about defaults differ between the zones:
- Before
*, a parameter without a default cannot follow one with a default.def f(a=1, b)is a SyntaxError. - After
*, keyword-only parameters are exempt from that rule.def f(*, a=1, b)is valid, because callers always name them.
def make_user(name, /, role="guest", *, active, tags=()):
return {"name": name, "role": role, "active": active, "tags": tags}
print(make_user("Ada", active=True))
# {'name': 'Ada', 'role': 'guest', 'active': True, 'tags': ()}Here active has no default and comes after tags' default sibling role. That is legal only because it is keyword-only.
Choosing which to use
| Situation | Choice |
|---|---|
| Boolean flags and options such as `timeout` | Keyword-only |
| A single obvious argument such as `len(x)` | Positional-only |
| Public API where names may change | Positional-only |
| Parameters that follow `*args` | Keyword-only (automatic) |
| Everything else | Leave as regular |
Do not apply either marker everywhere. Extra restrictions make a function harder to call and harder to wrap in decorators that forward *args, **kwargs.
Exercise
Write a function scale(value, /, factor=2, *, round_to=None) that returns value * factor, rounded with round() to round_to digits when round_to is not None. Which of these calls raise a TypeError: scale(3), scale(value=3), scale(3, 4, 1), scale(3, round_to=1)?
Show answer
Implementation: def scale(value, /, factor=2, *, round_to=None): then result = value * factor, and return result if round_to is None else round(result, round_to). scale(3) returns 6. scale(value=3) raises TypeError because value is positional-only. scale(3, 4, 1) raises TypeError because round_to is keyword-only and takes no third positional argument. scale(3, round_to=1) returns 6 and is valid.