liveBook · Manning

Default value

As explained in Python Workout, Second Edition

A default parameter is a function parameter that receives a specified fallback value when no argument is supplied.

A default value makes a function parameter optional: Python uses the specified fallback when the caller omits that argument. Parameters without defaults must come first, and extra arguments still raise an error. section 7.1

Use a default when the function has a known optional value:

  • def hello(name='world'): return f'Hello, {name}!' hello() # 'Hello, world!' hello('out there') # 'Hello, out there!' section 7.1
  • Put required parameters before defaulted ones. Prefer a default over *args when the function accepts one known optional value rather than an arbitrary number of values. section 7.1 section 7.3
  • Never use a mutable list or dict as a default: default objects are stored and reused, so mutations can leak between calls. section 7.1

Optional XML content

def myxml(tagname, content='', **kwargs): attrs = ''.join([f' {key}="{value}"' for key, value in kwargs.items()]) return f'<{tagname}{attrs}>{content}</{tagname}>' The required tagname is always supplied; content defaults to an empty string, while **kwargs handles separately named attributes. section 7.3

How Python Workout, Second Edition covers it

How deep it goes
Explains fallback calls, parameter ordering, function argument counts, and mutable-default reuse, but stops short of implementation internals beyond __code__.
Examples
Uses greeting calls and an XML-building function with optional content and keyword attributes.
What it assumes
Assumes familiarity with defining and calling functions rather than teaching function syntax from scratch.
What you can do after
Apply it via Python function definitions to support omitted arguments and known optional values.
How it connects
Connects default values with function definitions, *args, **kwargs, function objects, and mutable values.

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