Pre-PEP: Dictionary accumulator methods
El Pitonero
pitonero at gmail.com
Sat Mar 19 10:42:55 EST 2005
Dan Sommers wrote:
> On Sat, 19 Mar 2005 01:24:57 GMT,
> "Raymond Hettinger" <vze4rx4y at verizon.net> wrote:
>
> > The proposed names could possibly be improved (perhaps tally() is
more
> > active and clear than count()).
>
> Curious that in this lengthy discussion, a method name of
"accumulate"
> never came up. I'm not sure how to separate the two cases
(accumulating
> scalars vs. accumulating a list), though.
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]
More information about the Python-list
mailing list