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, it could look like this:
>>> from collections import Counter
>>> from random import randint, seed
>>> def gather_stats(n, samples=1000, summary=Counter()):
... summary.update(
... sum(randint(1,6) for d in range(n))
... for _ in range(samples))
... return summary
This shows a bad design for a function with two stories...