Pre-PEP: Dictionary accumulator methods

Raymond Hettinger vze4rx4y at verizon.net
Sat Mar 19 12:00:49 EST 2005


[El Pitonero]
> Is it even necessary to use a method name?
>
> import copy
> class safedict(dict):
>     def __init__(self, default=None):
>         self.default = default
>     def __getitem__(self, key):
>         try:
>             return dict.__getitem__(self, key)
>         except KeyError:
>             return copy.copy(self.default)
>
>
> x = safedict(0)
> x[3] += 1
> y = safedict([])
> y[5] += range(3)
> print x, y
> print x[123], y[234]



safedict() and variants have been previously proposed with the name defaultdict
or some such.

For the most part, adding methods is much less disruptive than introducing a new
type.

As written out above, the += syntax works fine but does not work with append().

As written, the copy.copy() approach is dog slow but can be optimized for lists
and ints while retaining its type flexibility.

BTW, there is no need to make the same post three times.


Raymond







More information about the Python-list mailing list