[Python-Dev] Split augmented assignment into two operator sets? [Re: SyntaxError: can't assign to function call]

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Aug 11 05:42:27 CEST 2006

Phillip J. Eby wrote:

> I think it's a warning sign because I *know* what augmented assignment's 
> semantics are supposed to be and I *still* try to use it with setdefault() 
> sometimes -- but only when I'm doing an augmented assignment.  I never 
> mistakenly try to assign to a function call in any other circumstance.

I think this problem arises because of the dual semantics
of augmented assignment. One tends to have two *different*
mental models of what it does, depending on whether the
object in question is immutable:

   (1) For immutable objects:

      x += y  <-->  x = x + y

   (2) For mutable objects:

      x += y  <-->  x.__iadd__(y)

and it's easy to forget that case (2) also happens
to have the side effect of assigning the result
back to x, which is usually redundant in the case
of an immutable object, and thus to slip into the
error of thinking that

      x(z) += y  <--->  x(z).__iadd__(y)

should be a reasonable thing to expect. And in
the case of a mutable result from x(z), it's
hard to argue convincingly that it's not

As to what this is a warning of, maybe it's that
the dual semantics were a mistake in the first
place, and that there really should have been
two sets of operators, e.g.

   x += y  <--->   x = x + y      # literally

   x +: y  <--->   x.__iadd__(y)  # with *no* assignment

The +: family of operators would then just be
normal infix operators, not assignments at all,
and one would be able to say

   x(z) +: y

without any trouble (provided the result of x(z)
were mutable, since immutables would not have
an __iadd__ method at all).

Another benefit to this is that the +: operators
would be usable on objects in an outer scope,
since they are not assignments and would therefore
not imply the localness of anything.

Something to consider for Py3k?

PS: Why an extra set of operators, rather than
ordinary methods? One of the motivations for the
augmented assignment operators was Numeric and the
desire to be able to express in-place operations
on arrays concisely. The +: family would fill this

PPS: Yes, I know the use of : might be ill-advised.
It's just an example - any other concise notation
would do as well.

Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | Carpe post meridiem!          	  |
Christchurch, New Zealand	   | (I'm not a morning person.)          |
greg.ewing at canterbury.ac.nz	   +--------------------------------------+

More information about the Python-Dev mailing list