liveBook · Manning

Default value

As explained in The Quick Python Book, Fourth Edition

A default parameter value is a value assigned to a function parameter and used when the corresponding argument is omitted from a call.

A default parameter value supplies an argument when a function call omits that parameter. It makes common cases shorter while preserving the option to provide a different value. section 9.2.1

Use default values with these rules:

  • Declare the value in the function definition, such as `def power(x, y=2):`. section 9.2.1
  • Place parameters with defaults after parameters without defaults in the parameter list. section 9.2.1
  • Omit the argument to accept the default, or pass an argument positionally or by parameter name to override it. section 9.2.1 section 9.2.2
  • Combine defaults with keyword arguments when a function has many optional settings; callers can select named options without depending on their order. section 9.2.2

A power function

def power(x, y=2): r = 1 while y > 0: r = r * x y = y - 1 return r power(3, 3) # 27 power(3) # 9 power(y=2, x=3) # 9 section 9.2.1 section 9.2.2

Optional file information

A function can default several Boolean options to false and enable selected behavior by name: `fileinfo = list_file_info(size=True, mod_date=True)`. This requests file size and modification date information without enabling creation-date information. section 9.2.2

Avoid mutating a mutable default such as `[]`. Python creates that default object when the function is first compiled and reuses it for the program’s lifetime, so later calls can inherit earlier mutations. section 9.3.1

odds = odd_numbers([1, 5, 7, 9, 10])
odds
 
[1, 5, 7, 9, 1, 5, 7, 9]

Run the repeated call to see the same default list accumulate values across invocations. section 9.3.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains declaration, positional ordering, keyword overrides, and mutable-object reuse, but stops short of implementation beyond compilation-time assignment.
Examples
Demonstrates exponentiation, named power arguments, optional file metadata, and an accumulating list default.
What it assumes
Assumes familiarity with function definitions, positional arguments, parameter names, and mutable objects.
What you can do after
Apply it by defining optional parameters, overriding defaults positionally or by name, and detecting mutable-default side effects.
How it connects
Connects default parameter values with positional parameters, keyword arguments, function calls, and mutable objects.

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 Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.