Keeping track of things with dictionaries

Frank Millman frank at chagford.com
Tue Apr 8 04:31:28 EDT 2014


"Ian Kelly" <ian.g.kelly at gmail.com> wrote in message 
news:CALwzidmP5Bevbace9GyQrVXe-_2T=jtPQ1yVaPsAePvOMQePLA at mail.gmail.com...
> On Tue, Apr 8, 2014 at 1:14 AM, Frank Millman <frank at chagford.com> wrote:
>>
>> It appears that when you use 'setdefault', the default is always 
>> evaluated,
>> even if the key exists.
>>
>> It seems odd. Is there a situation where this behaviour is useful?
>
> No.  The default argument is evaluated because it must be evaluated
> before it can be passed into the method, just like any other function
> argument in Python.  So why doesn't it take a callable instead of a
> value for its second argument?  At a guess, because the method was
> probably added for efficiency, and the function call overhead might
> easily be slower than just doing a separate getitem and setitem.
>
> The reason setdefault exists I think is primarily because it was added
> before defaultdict.  The contributors at SO can't seem to come up with
> any particularly good use cases either:
>
> http://stackoverflow.com/questions/3483520/use-cases-for-the-setdefault-dict-method
>
> One thing I will note as a disadvantage of defaultdict is that
> sometimes you only want the default value behavior while you're
> initially building the dict, and then you just want a normal dict with
> KeyErrors from then on.  defaultdict doesn't do that; once
> constructed, it will always be a defaultdict.  You can copy the data
> into a normal dict using the dict() constructor, but this feels dirty
> to me.

Here is an idea, inspired by Peter Otten's suggestion earlier in this 
thread.

Instead of defaultdict, subclass dict and use __missing__() to supply the 
default values.

When the dictionary is set up, delete __missing__ from the subclass!

Ugly, but it seems to work.

Frank






More information about the Python-list mailing list