Overriding iadd for dictionary like objects

Terry Reedy tjreedy at udel.edu
Fri Aug 28 23:42:04 CEST 2009


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.

> 
> 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.

[snip]
> As a workaround, if lookups are expensive,

But they are not. Because (C)Python is heavily based on dict name lookup 
for builtins and global names and attributes, as well as overt dict 
lookup, must effort has gone into optimizing dict lookup.

 > you can add

something even slower ;-).  In particular, a method lookup + method 
call, as you suggest above.

One can always avoid calculating the key object twice if that is expensive.

Terry Jan Reedy




More information about the Python-list mailing list