Pre-PEP: Dictionary accumulator methods

Christos TZOTZIOY Georgiou tzot at sil-tec.gr
Tue Mar 22 19:37:14 EST 2005


On Sat, 19 Mar 2005 01:24:57 GMT, rumours say that "Raymond Hettinger"
<vze4rx4y at verizon.net> might have written:

>I would like to get everyone's thoughts on two new dictionary methods:
>
>        def count(self, value, qty=1):
>            try:
>                self[key] += qty
>            except KeyError:
>                self[key] = qty
>
>        def appendlist(self, key, *values):
>            try:
>                self[key].extend(values)
>            except KeyError:
>                self[key] = list(values)

Both are useful and often needed, so I am +1 on adding such
functionality.  However, I am -0 on adding methods to dict.

I believe BJörn Lindqvist suggested a subtype of dict instead, which
feels more right.  I believe this is a type of 'bag' collection, and it
could go to the collections module.

The default argument 99% of the time is the same for all calls to
setdefault of a specific instance.  So I would suggest that the default
argument should be an attribute of the bag instance, given at instance
creation.  And since unbound methods are going to stay, we can use the
accumulator method as a default argument (ie int.__add__ or list.append)

Based on the above, I would suggest something like the following
implementation, waiting criticism on names, algorithm or applicability:)

.class bag(dict):
.    def __init__(self, accumulator=int.__add__):
.        self.accumulator = accumulator
.
.        # refinement needed for the following
.        self.accu_class = accumulator.__objclass__
.
.        # if there was an exception, probably the accumulator
.        # provided was not appropriate
.
.    def accumulate(self, key, value):
.        try:
.            old_value = self[key]
.        except KeyError:
.            self[key] = old_value = self.accu_class()
.        new_value = self.accumulator(old_value, item)
.
.        # and this needs refinement
.        if new_value is not None: # method of immutable object
.            self[key] = new_value

This works ok for int.__add__ and list.append.

PS I wrote these more than 36 hours ago, and before having read the
so-far downloaded messages of the thread.  I kept on reading and
obviously others thought the same too (default argument at
initialisation).

What the heck, Bengt at least could like the class method idea :)
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...



More information about the Python-list mailing list