Behavior of += (was Re: [Python-Dev] Customization docs)
John Roth
johnroth at ameritech.net
Mon Jun 3 18:32:34 EDT 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
> > > ([1], [2], [3])
> > > >>> t[1] += [3]
> > > Traceback (most recent call last):
> > > File "<stdin>", line 1, in ?
> > > TypeError: object doesn't support item assignment
> > > >>> t
> > > ([1], [2, 3], [3])
What I believe is going on here is that the list t[1]
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
they don't.
> >
> > Here's another that's differently wrong:
> > >>> a = ('aaa',)
> > >>> a[0]+='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.
John Roth
More information about the Python-list
mailing list