liveBook · Manning

Keyword-only parameter

As explained in Python How-To

A keyword-only argument is a function argument that must be supplied by explicitly naming its parameter rather than by position.

A keyword-only parameter must be supplied by naming it rather than by position. In a function definition, place an asterisk before the keyword-only parameters: def configure(name, *, verbose=False). Call it with configure("job", verbose=True); configure("job", True) is invalid. Naming the parameter makes the call's intent clearer, especially when several optional settings exist. section 6.4.1

A built-in example

The list.sort method uses sort(*, key=None, reverse=False). The defaults allow numbers.sort() to use ordinary ascending order, while numbers.sort(reverse=True) requests descending order. Passing True positionally, as in numbers.sort(True), is invalid because reverse is keyword-only. section 6.1.1

Use keyword-only parameters when:

  • Optional settings would be unclear when supplied only by position. section 6.4.1
  • A constructor has more than a few positional arguments; keep important arguments positional and make additional ones keyword-only. section 8.1.2
  • A variable-length positional parameter would otherwise consume arguments ambiguously. With def stringify_b(*items, item0), item0 must be written as a keyword, such as stringify_b(0, item0=1). section 6.4.2
numbers.sort(reverse=True)
 
assert numbers == [7, 5, 4, 2]

Inspect a focused call that activates a keyword-only option on list.sort. section 6.1.1

How Python How-To covers it

How deep it goes
Explains the asterisk syntax, call behavior, defaults, and interaction with *args, but stops short of implementation internals.
Examples
Demonstrates list.sort(reverse=True), constructor argument guidance, and stringify_b(*items, item0) calls.
What it assumes
Assumes basic function calls and parameters, while distinguishing positional, keyword, default, and variable-length arguments.
What you can do after
Apply it via Python function and method calls, and design clearer constructors with explicit optional settings.
How it connects
Connects keyword-only parameters with positional arguments, positional-only parameters, default arguments, variable-length arguments, and function design.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.