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























