Behavior of += (was Re: [Python-Dev] Customization docs)
johnroth at ameritech.net
Tue Jun 4 00:32:34 CEST 2002
"Steve Holden" <sholden at holdenweb.com> wrote in message
news:oWIK8.179611$%u2.31494 at atlpnn01.usenetserver.com...
> "Emile van Sebille" <emile at fenx.com> wrote ...
> > <jepler at unpythonic.net> wrote:
> > > IMO the following is an odder behavior:
> > > >>> t
> > > (, , )
> > > >>> t += 
> > > Traceback (most recent call last):
> > > File "<stdin>", line 1, in ?
> > > TypeError: object doesn't support item assignment
> > > >>> t
> > > (, [2, 3], )
What I believe is going on here is that the list t
is being updated since it's mutable, and then the
attempt to insert the new version of the list into the
tuple is being rejected - hence the error.
The fact that it shows the change is most likely due
to the list not having moved in memory. I hope that
the reference count was handled properly!
AFIC, this is clearly wrong - operators should
be atomic - no side effects. Either they work, or
> > Here's another that's differently wrong:
> > >>> a = ('aaa',)
> > >>> a+='bbb'
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> > TypeError: object doesn't support item assignment
> > >>> a
> > ('aaa',)
> > >>>
This is the exact same case, except that instead of
a list, the tuple contains a string - another immutable type.
Therefore, it fails on attempting to update the string,
rather than attempting to update the tuple.
Maybe. It might actually update the string, producing
'aaabbb' at a different location in memory,
and then (properly) fail to update the tuple.
More information about the Python-list