Why the defaultdict constructor accepts a function, not a constant

This is how defaultdict works:

from collections import defaultdict a=defaultdict(lambda:3) a[200]==3 #True 

Why was defaultdict created to accept a function with no arguments, and not just for a constant value?


Here is an alternative definition.

 class dd(dict): def __init__(self,x): self._default=x def __getitem__(self,key): if key in self: return key else: self[key]=self._default return self[key] 

So,

 a=dd(3) a[200]==3 #True 
+4
source share
1 answer

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.

+7
source

Source: https://habr.com/ru/post/1502143/


All Articles