liveBook · Manning

Keyword parameter

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A keyword parameter is a function parameter whose value is supplied by naming the parameter and which may have a default value.

A function call is easier to use when callers can change one optional detail without supplying every other option. In Python, a keyword parameter has a name and a default value. A caller can omit it to use the default or pass a value by name. This makes the function’s inputs part of a clear API contract. section 3.1.2 section 3.2.2

Consider a name-building function with a required first name and optional middle and last names. Its parameter list can be written as `full_name(fname, mname=None, lname=None)`. A caller can supply just a first name or specify `lname` while leaving `mname` at its default. The function must handle omitted names appropriately; a default of `None` does not, by itself, format the result. section 3.2.2

Supply only the option you need

`full_name("John", lname="Smith")` supplies the required `fname` positionally and `lname` by name. `mname` keeps its default of `None`. Named arguments can also be supplied in a different order from the parameter definition. section 3.2.2

Defaults also keep an API compact. Python’s `print` accepts multiple objects and has named options including `sep=' '`, `end='\n'`, and `file=sys.stdout`. A simple call uses those defaults; a call that needs a different separator or destination changes the relevant option rather than requiring a separate printing function. When defining parameters, put required parameters before default-valued ones: after a parameter with a default, following parameters must have defaults too. section 3.1.2 section 3.2.2

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Explains defaults, named calls, reordered arguments, and parameter-definition order through function examples, without examining Python implementation internals.
Examples
Uses a name-building function and Python’s `print` options to show omitted defaults and arguments supplied by name.
What it assumes
Assumes familiarity with basic Python function calls while distinguishing arguments from parameters and showing how positional and keyword inputs differ.
What you can do after
Build it from scratch by defining default-valued Python parameters and calling functions with named arguments when optional inputs vary.
How it connects
Connects keyword parameters to positional parameters, default values, function signatures, and API contracts.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.