liveBook · Manning

Default value

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

A default value is a value automatically assigned to a function parameter when the caller does not provide that parameter.

A default value lets a function work when a caller leaves out an optional argument. This keeps the common call short without removing the caller’s ability to choose a different value. Python’s print(), for example, separates items with spaces unless you supply another sep value. section 3.1.2

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The print() signature shows its defaults together: a space separator, a newline ending, standard output as the destination, and flushing turned off. section 3.1.2

Make part of a name optional

Start with a full_name function that requires a first, middle, and last name. Give mname and lname defaults of None, and fname becomes the only required argument. A caller can then provide a last name without providing a middle name, as in full_name("John", lname="Smith"). The function’s body must still decide how to format a missing name. section 3.2.2

Put required parameters before parameters with defaults: once a parameter has a default, those following it must have defaults too. A related use appears in SQLAlchemy model columns, where a default can supply a value for a new row. A Post column uses get_next_sort_key to generate its sort order; that is a column default, not a function-parameter default. section 3.2.2 section 11.7.1

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

How deep it goes
Explains omitted arguments, keyword overrides, and parameter ordering, but does not examine default-evaluation internals.
Examples
Uses print() options and a full_name function with optional middle and last names.
What it assumes
Assumes familiarity with basic Python function calls while explaining positional and keyword arguments.
What you can do after
Practice/perform it by defining optional Python parameters and overriding named options when calling a function.
How it connects
Connects default values to API design, positional arguments, keyword arguments, and SQLAlchemy column defaults.

Also explained in

Compare how 20 books explain default value →

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.