Positional-Only And Keyword-Only Markers
The / marker forces positional-only arguments and * forces keyword-only ones, so call sites stay self-documenting and misorders fail loudly.
Code
def report(name, /, role, *, level="info"):
# name: positional-only (before /) — callers must not write name=
# level: keyword-only (after *) — callers must not pass it positionally
return f"{name}:{role}:{level}"
print(report("ci-bot", "deployer", level="warn"))
print(report("ci-bot", role="deployer"))
print(report("ci-bot", "deployer"))
# Keyword-only params make call sites self-documenting and reorder-safe
try:
report("ci-bot", "deployer", "warn")
except TypeError as exc:
print("positional overflow:", exc)
# Positional-only names reject keyword spellings too
try:
report(name="ci-bot", role="runner")
except TypeError as exc:
print("positional-only:", exc)Output
Captured from a sandboxed run of this snippet in the build pipeline.
ci-bot:deployer:warn
ci-bot:deployer:info
ci-bot:deployer:info
positional overflow: report() takes 2 positional arguments but 3 were given
positional-only: report() got some positional-only arguments passed as keyword arguments: 'name'How the snippet works
Structurally, expect the function report and nothing else.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
Using it
Entry signature: def report(name, /, role, *, level="info")
Output lines are prefixed (positional overflow:, positional-only:), making each step’s effect easy to spot.
Callers only need report — everything else stays internal.
The key statements, annotated
def report(name, /, role, *, level="info"):
# name: positional-only (before /) — callers must not write name=
# level: keyword-only (after *) — callers must not pass it positionally
return f"{name}:{role}:{level}"
except TypeError as exc:
print("positional overflow:", exc)
except TypeError as exc:
print("positional-only:", exc)
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `report` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.