Behavior of += (was Re: [Python-Dev] Customization docs)

Steve Holden sholden at holdenweb.com
Mon Jun 3 07:59:05 EDT 2002


"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])
> >
>
> Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
> >>> class myTuple(tuple):
> ...     def __setitem__(self, attr, value):
> ...             print 'in setitem:', attr
> ...
> >>> a = myTuple(([1],[2],[3]))
> >>> a
> ([1], [2], [3])
> >>> a[1] += [4]
> in setitem: 1
> >>> a
> ([1], [2, 4], [3])
> >>>
>
>
> 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',)
> >>>


Why do you consider either of these examples wrong? The whole point of
tuples is that if d is a dictionary, then d[t1] == d[t2] if, and only if, t1
== t2. Both of these examples are trying to make changes that will modify an
(immutable) tuple. There's every reason to treat these modifications as
illegal, since a before the fiddling is not equal to a after the fiddling,
but tuples aren't mutable so such changes are illegal.

regards
--
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list