Augmented assignment (was Re: Something in the function tutorial confused me.)
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Sat Aug 11 14:04:07 EDT 2007
OKB (not okblacke) schreef:
> 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.
The way I understand this now, the assignment really always is an
assignment.
1.
- For immutable objects, the 'binary operation specific to the type of
assignment on the two operands' doesn't modify any object, but only
returns a new object which is the result of the operation.
- For mutable objects that support the inplace-version of the
operator, the operator modifies the object and then returns it.
3. In both cases that result is assigned to the target. In the second
case the object was already modified so the assignment doesn't
accomplish very much, but it still happens.
That explains why "tup[0] += ['zap']" both has an effect (tup[0] now
contains 'zap') and raises an exception: tup[0] is modified because it
is a list and lists support inplace addition, but the assignment fails
because tuples don't support item assignment.
--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton
Roel Schroeven
More information about the Python-list
mailing list