Overriding iadd for dictionary like objects

Robert Kern robert.kern at gmail.com
Fri Aug 28 18:13:19 EDT 2009


On 2009-08-28 16:42 PM, Terry Reedy wrote:
> Carl Banks wrote:
>
>> I don't think it needs a syntax for that, but I'm not so sure a method
>> to modify a value in place with a single key lookup wouldn't
>> occasioanally be useful.
>
> Augmented assignment does that.

No, it uses one __getitem__ and one __setitem__ thus two key lookups.

>> For instance:
>>
>> def increment(value):
>> return value+1
>> d = { 'a': 1 }
>> d.apply_to_value('a',increment)
>> print d
>>
>> and d['a'] would be 2. The difference is that only one lookup
>> occurs.
>
> Like this?
>  >>> d={'a': 2}
>  >>> d['a'] += 2
>  >>> d['a']
> 4
>
> This does not cover all replacements, but certainly the most common.

Take look farther up in the thread for the actual point at issue. The OP knows 
that augmented assignment works for the common cases. He wants to override the 
behavior on the container to handle some uncommon cases, and this is not 
possible because Python breaks up the operation into three orthogonal actions.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list