Overriding iadd for dictionary like objects

Carl Banks pavlovevidence at gmail.com
Fri Aug 28 19:02:00 EDT 2009


On Aug 28, 2:42 pm, Terry Reedy <tjre... at udel.edu> 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.

Internally uses two lookups, one for getting, and one for setting.  I
think this is an unavoidable given Python's semantics.  Look at the
traceback:


>>> def x():
...     d['a'] += 1
...
>>> dis.dis(x)
  2           0 LOAD_GLOBAL              0 (d)
              3 LOAD_CONST               1 ('a')
              6 DUP_TOPX                 2
              9 BINARY_SUBSCR
             10 LOAD_CONST               2 (1)
             13 INPLACE_ADD
             14 ROT_THREE
             15 STORE_SUBSCR
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE


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

The actual lookup algorithm Python dicts use is well-optimized, yes,
but the dict could contain keys that have expensive comparison and
hash-code calculation, in which case lookup is going to be slow.


Carl Banks



More information about the Python-list mailing list