[Python-Dev] behavior of inplace operations

Tim Peters tim.one@comcast.net
Sun, 16 Jun 2002 21:13:21 -0400


[David Abrahams]
> ...
> The pathological/non-generic cases are> the ones that make me think twice
> about using the inplace ops at all. They don't, in fact, "just work", so
> I have to think carefully about what's happening to avoid getting myself
> in trouble.

I didn't understand this thread.  The inplace ops in Python do "just work"
to my eyes, but I expect them to work the way Python defines them to work,
which is quite uniform.  For example,

    e1[e2] += e3

acts like

    t0, t1 = e1, e2
    t0[t1] = t0[t1] + e3

There's no guarantee that e1[e2] as a whole is evaluated at most once, and,
to the contrary, the subscription is performed twice, just like the "acts
like" line implies.  Likewise

    e1.id += e2

acts like

    t0 = e1
    t0.id = t0.id + e3

The way an augmented assignment in Python works is defined by cases, on the
form of the target.  Those were the "subscription" and "attributeref" forms
of target.  There are two other relevant forms of target, "identifier" and
"slicing", and they're wholly analogous.  Note an implication:  in a
"complicated" target, it's only the top-level subscription or attribute
lookup that gets evaluated twice; e.g.,

    e1[e2].e3[e4] += e5

acts like

    t0, t1 = e1[e2].e3, e4
    t0[t1] = t0[t1] + e5

Note that Python doesn't have a reference-to-lvalue concept.  If you don't
believe "but it should, so I'm going to think as if it does", there's
nothing surprising about augmented assignment in Python.  Indeed, I'm not
even surprised by what this prints <wink>:

>>> a = range(12)
>>> a[2:9] += [666]
>>> a