TypeError expected in an augmented assignment

Chris Angelico rosuav at gmail.com
Thu Jul 3 10:36:49 CEST 2014


On Thu, Jul 3, 2014 at 5:51 PM, candide <c.candide at laposte.net> wrote:
> Good and interesting observation. But I can't find out where this feature is referenced in the Language/Library Reference. Because, as my first post explains, augmented assignment performs the binary operation associated to the augmented assignment, cf.
>
> https://docs.python.org/3.2/reference/simple_stmts.html#augmented-assignment-statements
>
> so seq+= {5, 6} performs seq + {5, 6}, the later raising a TypeError.

>From that link:

"""
An augmented assignment expression like x += 1 can be rewritten as x =
x + 1 to achieve a similar, but not exactly equal effect. In the
augmented version, x is only evaluated once. Also, when possible, the
actual operation is performed in-place, meaning that rather than
creating a new object and assigning that to the target, the old object
is modified instead.
"""

The significance here is that the augmented assignment may not
necessarily be at all comparable to the non-augmented version, but
ought to have *approximately* the same *intention*. There are plenty
of situations where the two will differ, eg when there are multiple
references to the same object:

>>> a = b = [1,2]
>>> a += [3]
>>> a,b
([1, 2, 3], [1, 2, 3])
>>> a = a + [4]
>>> a,b
([1, 2, 3, 4], [1, 2, 3])

In its simplest form, x += 1 <-> x = x + 1, but there are plenty of
ways to distinguish them.

ChrisA



More information about the Python-list mailing list