Because if you want the default value to be a mutable object, you probably want it to be a different mutable object for each key.
If you passed a constant and made defaultdict([])
, then every time there was no access to the key, its value would be set to the same list. Then you get the following:
>>> d = defaultdict([]) >>> d[1].append("Whoops") >>> print d[2] ["Whoops"]
Having a mutable default value is actually very common and useful, as it allows you to do things like d[key].append("Blah")
without checking that d[key]
exists. For this case, you need to somehow return a new value each time, and the easiest way to do this is to call the caller, which returns the default value.
source share