Augmented assignment (was RE: [Python-Dev] Re: Is it just Syntactic Sugar ?)

Tim Peters tim_one@email.msn.com
Mon, 5 Jun 2000 22:09:22 -0400


[posted & mailed]

[Thomas Wouters, asking about Guido's sketch]
> This was what I had in mind, and was trying to explain. Does you
> voicing your opinion mean someone (you ? someone else ?) is working
> on this, or soon going to work on this ?

It's the same scheme he sketched the last time he was provoked into writing
about this <wink>, and that was at least a year ago.

> ...
> I'm curious what should happen with index-assignment and
> slice-assignment:

Nothing special!  You're reading far too much into Guido's sketch -- it
doesn't have all these convolutions.  Try reading his msg again, but this
time thinking like him too <wink>.

> x[y] += z

temp1 = x  # perhaps the first three are permuted, though
temp2 = y
temp3 = z
temp1[temp2] = temp1[temp2].__add_ab__(temp3)

And, yes, indexing is done twice (although "x" and "y" are evaluated only
once each).

> x[:y] += z

temp1 = x
temp2 = y
temp3 = z
temp1[:temp2] = temp1[:temp2].__add_ab__(temp3)

Similarly slicing is done twice.

> (Obviously this wont make sense for a lot of types, or will be too
> un-obvious to include, but I can imagine matrix-types to happily
> add this.)

Every type is free to implement __add_ab__ or not, in whatever way it likes.
But Python can't tell at compile-time which types do and don't implement it,
so chances are great that doing

   x += y

for x of a type that does not implement __add_ab__ will raise a runtime
AttributeError.

> Would this call x.__add_item_ab__(y, z) and x.__add_slice_ab__(0,
> y, z) ?

No.  *All* instances of "+=" are mapped straightforwardly to __add_ab__.
Context is irrelevent; indexing and slicing are not special cases (except to
the extent that they are already ...).

> Or would x[y] += z always call x[y].__add_item_ab__()

No.

> and x[:y] create a new object, a slice of x

What x[:y] means is entirely up to the type of x, and has no connection to
augmented assignment (except in that the author of the type may design both
to work smoothly together).

> and call its __add_ab__() method ?

__add_ab__ would be invoked on whatever x[:y] returns; whether that's "a new
object" or not is x.__get_slice__'s choice to make.

> Or would it try all of them, or more, until it gets a good result ?

No.  It works or it doesn't.

> Or am I running ahead of things and should we wait for a working
> patch first ? :)

No, you're running a few years behind things <wink>, and imagining
complications Guido would never sign up for.

and-now-the-spirits-must-rest-ly y'rs  - tim