liveBook · Manning

Side effect

As explained in Python How-To

A side effect is an observable state change produced by evaluating or calling an operation in addition to its returned result.

A side effect is an observable state change produced by evaluating or calling an operation in addition to its returned result. In Python, recognizing hidden state changes helps you choose clearer, more maintainable code. section 3.4.5 section 6.1.3

Common Python examples include:

  • Calling dict.setdefault(key, default) inserts the missing key and default value, even though the call looks like a lookup. section 3.4.5
  • Defining a function with a mutable default creates that object during function evaluation; later calls can mutate the same list. section 6.1.3
  • Prefer explicit operations and use None as the default for mutable parameters, creating a fresh list inside the function. section 3.4.5 section 6.6

A shared mutable default

def complete_task(task, grouped_tasks=None): if grouped_tasks is None: grouped_tasks = [] grouped_tasks.append(task.title) return grouped_tasks Each call that omits grouped_tasks now receives a new list, avoiding the surprising result where separate calls share ['Homework', 'Fishing']. section 6.1.3 section 6.6

urgencies = {"Laundry": 3, "Homework": 5, "Museum": 2}
urgencies.setdefault("Homework")
# output: 5

urgencies.setdefault("Homeworks", 0)
# output: 0

urgencies.setdefault("Grocery")
# output: None (None is automatically hidden in an interactive console)

Inspect setdefault calls that return values while silently adding missing dictionary entries. section 3.4.5

How Python How-To covers it

How deep it goes
Explains implicit dictionary insertion and shared mutable defaults, then stops at practical prevention rather than language implementation internals.
Examples
Uses setdefault dictionary entries and complete_task calls that unexpectedly share a mutable list.
What it assumes
Assumes basic dictionaries and functions while demonstrating default arguments, object identity, and mutable-state behavior.
What you can do after
Diagnose unexpected mutations and prevent them with explicit dictionary updates or None-based mutable defaults.
How it connects
Connects side effects to setdefault, dictionary mutation, function evaluation, mutable default arguments, and default values.

Also explained in

Compare how 24 books explain side effect →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.