Augmented assignment (was Re: Something in the function tutorial confused me.)

OKB (not okblacke) brenNOSPAMbarn at NObrenSPAMbarn.net
Sat Aug 11 13:47:08 EDT 2007


Aahz wrote:

>>>>>> tup=([],)
>>>>>> tup[0] += ['zap']
>>> Traceback (most recent call last):
>>>   File "<stdin>", line 1, in <module>
>>> TypeError: 'tuple' object does not support item assignment
<snip>
> Obviously, you can easily work around it:
> 
>>>> t = ([],)
>>>> l = t[0]
>>>> l += ['foo']
>>>> t
> (['foo'],)

    	This is quite shocking to me, although after staring at the 
documentation for a while I guess I understand it.  But it seems to me 
that the documentation is somewhat misleading on this point, where it 
says:

    	"An augmented assignment evaluates the target (which, unlike normal 
assignment statements, cannot be an unpacking) and the expression list, 
performs the binary operation specific to the type of assignment on the 
two operands, and assigns the result to the original target."

    	This sentence is phrased as though it is the whole story, but it 
isn't, because the operation might not in fact wind up being an 
assignment.  Shouldn't there be an "except see below" or something 
there, to alert the reader that in some cases a true assignment doesn't 
occur?  (I realize that the exception follows quite closely on the heels 
of this sentence, but it doesn't follow immediately, and is separated by 
a paragraph break and intervening material about the parallel to 
unaugmented x = x + 1.  On initial reading my tendency is to read the 
end of the sentence quoted above, see a paragraph break and apparently 
explanatory material, and go "oh, okay, I now have the full 
specification of this syntax" when in fact I don't.)
   	
-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown



More information about the Python-list mailing list