Overriding iadd for dictionary like objects

RunThePun ubershmekel at gmail.com
Thu Aug 27 08:49:10 CEST 2009


On Aug 27, 6:58 am, Robert Kern <robert.k... at gmail.com> wrote:
> On 2009-08-26 20:00 PM, Jan Kaliszewski wrote:
>
>
>
>
>
> > 27-08-2009 o 00:48:33 Robert Kern <robert.k... at gmail.com> wrote:
>
> >> On 2009-08-26 17:16 PM, RunThePun wrote:
> >>> I'd like to build a database wrapper using DictMixin and allow items
> >>> to be appended by my own code. The problem is += is always understood
> >>> as setitem and getitem plainly.
>
> >>> d = MyDict()
> >>> d['a'] = 1
>
> >>> # this is the problem code that's I'd like to override. It's always
> >>> setitem('a', getitem('a') + 3)
> >>> d['a'] += 3
> >>> # i wanted to do something like my own 'appenditem' function which for
> >>> example could be useful if getitem is an expensive operation which can
> >>> be avoided.
>
> >>> I hope that was clear enough of a request, it's really late at night
> >>> here...
>
> >> I'm sorry, this is just part of the syntax of Python. You cannot
> >> override it.
>
> > Though
> > d['a'] = 3
> > is equivalent to:
> > d.__setitem__('a', 3)
>
> > The
> > d['a'] += 3
> > *is not* equivalent to:
> > d.__setitem__('a', d.__getitem__('a') + 3)
> > *but is* equivalent to:
> > d.__getitem__('a').__iadd__(3)
>
> > Then you can override __getitem__() of MyDict in such a way that it
> > returns prepared (wrapped) object with overriden __iadd__() as you
> > want to.
>
> You could, but then you will almost certainly run into problems using the
> wrapped object in places that really expect the true object.
>
> --
> 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

Exactly my problem Robert. I'm actually going to be using this dict
for storing and retrieving strings so wrapping str and replacing the
iadd would cause alot of craziness.

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

---RP



More information about the Python-list mailing list