dict.setdefault() (Patch#101102) (was: Re: [Python-Dev] Re: A
small proposed change to dictionaries' "get" method...)
Greg Ewing
greg@cosc.canterbury.ac.nz
Tue, 08 Aug 2000 15:08:48 +1200 (NZST)
artcom0!pf@artcom-gmbh.de:
> dict.setdefault('key', [])
> dict['key'].append('bar')
I would agree with this more if it said
dict.setdefault([])
dict['key'].append('bar')
But I have a problem with all of these proposals: they require
implicitly making a copy of the default value, which violates
the principle that Python never copies anything unless you
tell it to. The default "value" should really be a thunk, not
a value, e.g.
dict.setdefault(lambda: [])
dict['key'].append('bar')
or
dict.get_or_add('key', lambda: []).append('bar')
But I don't really like that, either, because lambdas look
ugly to me, and I don't want to see any more builtin
constructs that more-or-less require their use.
I keep thinking that the solution to this lies somewhere
in the direction of short-circuit evaluation techniques and/or
augmented assignment, but I can't quite see how yet.
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury, | A citizen of NewZealandCorp, a |
Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. |
greg@cosc.canterbury.ac.nz +--------------------------------------+