PATCH: Augmented assignment

Thomas Wouters thomas at xs4all.net
Fri Jun 9 19:01:03 EDT 2000


On Fri, Jun 09, 2000 at 10:39:29PM +0000, Rainer Deyke wrote:
> Warren B. Focke <moron at Glue.umd.edu> wrote in message
> news:8hrdkn$3uf at stochastic.eng.umd.edu...
> > But it does.  Accessing an attribute of an object or an item in a
> > container type can invoke arbitrary code, with arbitrarily freakish
> > side effects.  Evaluating x[17] might suck up hours of CPU time and
> > gibibytes of RAM, redefine builtin functions, launch the missiles, or
> > annoy your mother.  Having all of these things happen once, as in
> > x[17] += 1, is much preferable to, and potentially significantly
> > different from, having them happen twice, as in x[17] = x[17] + 1.
> > It's not just syntactic sugar that

> What if x is a database that loads an object from file on __getitem__ and
> writes it on __setitem__?  Then x[17] += 1 would work correctly only if
> x[17] has no += operation defined and the interpreter falls back on
> executing x[17] = x[17] + 1.

Well, I can't speak for other patches<0.7wink> but in the patch I wrote, and
in any patch that would make sense, 'x[17] += 1' still triggers a
__getitem__ *and* a __setitem__. It's probably easiest to see the
augmented-assignment syntax as a macro rewrite (which it isn't, because it's
a single opcode, which makes it threadsafe.) Looking at it like that,

x[spam(y, 10)-1] += 10 + eggs(10)

would not turn into:

x.__magical_getset_item__(spam(y, 10) - 1, 10 + eggs(10))

which you seem to think (and I thought, before Tim straightened me out), but
in the much simpeler:

index = spam(y, 10) - 1 # The exact order of evaluation of index and rhs
addval = 10 + eggs(10)  # elude me at this moment -- it's late.

x[index] = x[index].__add_ad__(addval)

The __add_ad__ method (or the C-API-variant of it) can decide for itself, on
a case to case basis, wether to return 'self' or a new object.

This way of looking at it makes it very simple, and to me, very natural. Of
course, it may take people a little getting used to, but I dont really see a
reason for it to remain as incomprehensible as, say, regular expressions or
the difference between __getattr__ and __setattr__. (I'll purposely ommit
''.join() in that list ;-)

It's-all-very-logical-in-bytecode-ly yr's,

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list