[Python-ideas] Yet Another Switch-Case Syntax Proposal

Terry Reedy tjreedy at udel.edu
Sat Apr 26 21:38:01 CEST 2014


On 4/26/2014 10:44 AM, Philipp A. wrote:
> interesting. it’s still assignment, even if nothing gets assigned (and
> only |__iadd__| gets called behind the scenes).

Augmented assignment statements are specialized assignment statements. 
They are documented in a subsection of the assignment statement section.
https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements
Something is always rebound, even if it is the same object. The 
interpreter does not know whether __iadd__ will return the same object 
or a new object -- and it does not check after.

Not understanding that augmented assignment always assigns trips up 
beginners who mistakenly and unnecessarily try to use it to mutate a 
member of a tuple.

 >>> t = ([],)
 >>> t[0] += [1,2]
Traceback (most recent call last):
   File "<pyshell#1>", line 1, in <module>
     t[0] += [1,2]
TypeError: 'tuple' object does not support item assignment
 >>> t
([1, 2],)

This is equivalent to* and effectively executed as

 >>> t = ([],)
 >>> t[0] = t[0].__iadd__ ([1,2])
Traceback (most recent call last):
   File "<pyshell#13>", line 1, in <module>
     t[0] = t[0].__iadd__ ([1,2])
TypeError: 'tuple' object does not support item assignment
 >>> t
([1, 2],)

* The difference is that 't' is only evaluated once and the resulting 
reference is used for both subscriptions.

The proper way to mutate a tuple member is to directly mutate it.

 >>> t = ([],)
 >>> t[0].extend([1,2])
 >>> t
([1, 2],)

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list