Skip to content Skip to sidebar Skip to footer

Defaultdict Constant_factory Doesn't Behave As Expected

I'm willing to use defaultdict with an ad hoc default_factory which suits better my purpose. The default_factory would be [0,0]. I've implemented a constant_factory function: def c

Solution 1:

First of all, just use:

defaultdict(lambda: [0, 0])

Your rather elaborate callable returns the same list over and over again. You are using the same list for all values in your dictionary. The above lambda returns a new list each time it is called instead:

>>> import itertools
>>> lambda_default = lambda: [0, 0]
>>> iter_default = itertools.repeat([0, 0]).next
>>> lambda_default() is lambda_default()
False
>>> iter_default() is iter_default()
True

You thus fill your dictionary with references to one list, and altering values in that one list is reflected everywhere the reference to that one list is printed.


Post a Comment for "Defaultdict Constant_factory Doesn't Behave As Expected"