Pre-PEP: Dictionary accumulator methods

Ron radam2 at tampabay.rr.com
Mon Mar 21 00:21:56 EST 2005


On Sun, 20 Mar 2005 15:14:22 -0800, David Eppstein
<eppstein at ics.uci.edu> wrote:

>In article <d1koii$2vp$1 at panix2.panix.com>, aahz at pythoncraft.com (Aahz) 
>wrote:
>
>> >I am surprised nobody suggested we put those two methods into a
>> >separate module (say dictutils or even UserDict) as functions:
>> >
>> >from dictutils import tally, listappend
>> >
>> >tally(mydict, key)
>> >listappend(mydict, key, value)
>> 
>> That seems like a reasonable compromise.
>
>The more messages I see on this thread, the more I think adding a 
>different new method for each commonly used kind of update is the wrong 
>solution.
>
>We already have methods that work pretty well and, I think, read better 
>than the new methods:
>  mydict[key] += 1
>  mydict[key].append(value)
>The problem is merely that they don't work when key is missing, so we 
>need to resort to setdefault circumlocutions instead.  A better solution 
>seems to be the one I've seen suggested here several times, of changing 
>the dict's behavior so that the setdefault is automatic whenever trying 
>to access a missing key.  If this would be in a separate module or 
>separate subclass of dict, so much the better.


I think that the setdefault behavior needs to be done on an per
application basis because whose to say what default is best?.

With a preset default mode, it then becomes possible to  inadvertently
create default values that will cause problems without knowing it.  So
then we have to remember to change the setdefault value to None or
null to avoid problems.  Ouch!

Also pythons normal behavior for retrieving objects that are not
defined is to give an error.  So having dictionaries that auto
defaults to a mode that doesn't behave that way is inconsistent with
the rest of the language.

Yet,  I'm all for the creation of specialized containers in a standard
module!  :)  Then we can have string dicts, and int dicts, and card
dicts, account dicts, etc, as well as specialized lists.  Call them
'smart containers'.  But they should not be built into the base class.

Ron




More information about the Python-list mailing list