Overriding iadd for dictionary like objects

Carl Banks pavlovevidence at gmail.com
Fri Aug 28 22:03:40 CEST 2009


On Aug 26, 11:49 pm, RunThePun <ubershme... at gmail.com> wrote:
> Anybody have any more ideas? I think python should/could havev a
> syntax for overriding this behaviour, i mean, obviously the complexity
> of supporting all operators with the getitem syntax could introduce
> alot of clutter. But maybe there's an elegant solution out there...

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.

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.  (The dictionary would be locked to modifications while the
callback function is called, same as if it were being iterated over.)

Thing is, there's no way to get that ability except subclass dict in
C; can't be done from Python.  Which is why even though it'd be a
pretty rare need it at least deserves a bit of consideration before
being tabled.

As a workaround, if lookups are expensive, you can add an indirection
to the dict.  For example, you could let each value in the dict be a
singleton list which is permanently bound to the key.  Then you only
have look up the key once to modify the value.

    d = { 'a': [1] }
    ston = d['a']
    ston[0] += 3

and now d['a'][0] is 4, and there was only one dict lookup.  Downside
is that you have the [0] to carry around, but that is the price of
indirection.  A wrapper class might help.


Carl Banks



More information about the Python-list mailing list