Pre-PEP: Dictionary accumulator methods

Michael Spencer mahs at telcopartners.com
Sat Mar 19 23:38:44 EST 2005


Kay Schluehr wrote:

> Maybe also the subclassing idea I introduced falls for short for the
> same reasons. Adding an accumulator to a dict should be implemented as
> a *decorator* pattern in the GoF meaning of the word i.e. adding an
> interface to some object at runtime that provides special facilities.
> 
> Usage:
> 
> 
>>>>d = intdict(extend=MyAccumulator)
>>>>hasattr(d,"tally")
> 
> True
> 
>>>>hasattr(d,"appendlist")
> 
> False
> 
> This could be generalized to other fundamental data structures as well.
> 
> Regards Kay
> 
Or similarly, something like the 'reversed' view of a sequence:

I could imagine a class: accumulator(mapping, default, incremetor) such that:
  >>> my_tally = accumulator({}, 0, operator.add)
  or
  >>> my_dict_of_lists = accumulator({}, [], list.append)
or
  >>> my_dict_of_sets = accumulator({}, set(), set.add)

then: .accumulate(key, value) "does the right thing" in each case.

a bit cumbersome, because of having to specify the accumulation method, but 
avoids adding methods to, or sub-classing dict

Michael








More information about the Python-list mailing list