Avoiding mutable default values for function parameters
In Chapter 3, Function Definitions, we looked at many aspects of Python function definitions. In the Designing functions with optional parameters recipe, we showed a recipe for handling optional parameters. At the time, we didn't dwell on the issue of providing a reference to a mutable structure as a default. We'll take a close look at the consequences of a mutable default value for a function parameter.
Getting ready
Let's imagine a function that either creates or updates a mutable Counter
object. We'll call it gather_stats()
.
Ideally, a small data gathering function could look like this:
import collections
from random import randint, seed
from typing import Counter, Optional, Callable
def gather_stats_bad(
n: int,
samples: int = 1000,
summary: Counter[int] = collections.Counter()
) -> Counter[int]:
summary.update(
sum(randint(1, 6)
for d in range...