liveBook · Manning

Named argument

As explained in Python Workout, Second Edition

A keyword argument is an argument passed by associating a value with a parameter name in a function call.

A named argument passes a value by associating it with a parameter name, using the name=value form. Python treats these arguments separately from positional arguments, making calls clearer and functions more flexible. section 7.0 section 7.3

Use named arguments when a function should accept optional or extensible values:

  • Define an optional parameter with a default when one named value has a natural fallback. section 7.3
  • Collect arbitrary named arguments with **kwargs; Python stores the names and values in a dictionary. section 7.3
  • Iterate over kwargs.items() when each supplied name-value pair must be transformed or validated. section 7.3
  • Use supplied names as dynamic options, such as menu commands or query criteria like color and legs. section 9.7 section 10.36
def myxml(tagname, content='', **kwargs):
    attrs = ''.join([f' {key}="{value}"'
                     for key, value in kwargs.items()])
    return f'<{tagname}{attrs}>{content}</{tagname}>'

A compact implementation combines a required tag name, optional content, and arbitrary named attributes. section 7.3

How Python Workout, Second Edition covers it

How deep it goes
Explains name-value syntax, default parameters, kwargs dictionary construction, iteration, and practical transformations.
Examples
Demonstrates XML attributes, dynamically constructed menus, and animal queries filtered by color or legs.
What it assumes
Assumes familiarity with functions and dictionaries while contrasting named arguments with positional arguments.
What you can do after
Apply it via Python function calls to design extensible interfaces and process caller-supplied options by name.
How it connects
Connects named arguments with default arguments, variable-length arguments, dictionaries, dispatch tables, and function parameters.

Also explained in

Compare how 3 books explain named argument →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.