5.6 Avoiding mutable default values for function parameters
In Chapter 3, 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.
5.6.1 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:
from collections import Counter 
 
from random import randint, seed 
 
 
 
def gather_stats_bad( 
 
    n: int, 
 
    samples: int = 1000, 
 
    summary: Counter[int] = Counter... 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                