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

Emile van Sebille emile at fenx.com
Mon Jun 3 09:48:56 EDT 2002


Steve Holden
> Steve Holden
> > 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.

No.  They're using a reference to a mutable held in a tuple to modify
the mutable in-place.

> >There's every reason to treat these modifications as
> > illegal, since a before the fiddling is not equal to a after the
fiddling,

This is true in the case of re-assignment, as in t[0]=t[0]+1, but
shouldn't be in the case of in-place using += which is why I'd consider
it wrong.  Moreover, the first example completes the change *and*
produces a traceback!

> > but tuples aren't mutable so such changes are illegal.

The tuple shouldn't be modified.  The object pointed to by a reference
held in the tuple should.

> >
> > regards
> > --
>
> ----------------------------------------------------------------------
-
> > Steve Holden
http://www.holdenweb.com/
> > Python Web Programming
http://pydish.holdenweb.com/pwp/
>
> ----------------------------------------------------------------------
-
> >
> The dictionary example is somewhat misleading (because my assertion is
> wrong). However, I stand by the statement that you are both trying to
modify
> tuples, which is fundamentally against the nature of the type.
>

Why is changing an underlying mutable object using a reference held in a
tuple against the nature of a tuple?  It works just fine like this:
>>> t = ([1],[2],[3])
>>> t[1][0]=4
>>> t
([1], [4], [3])
>>> t[1][0]=t[1][0]+4
>>> t
([1], [8], [3])
>>> t[1][0]+=4
>>> t
([1], [12], [3])

Except the in-place extension of a list:

>>> t[1][0]=t[1][0]+[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand types for +
>>>

But, in-place extensions of lists works without changing the id's:

>>> t1 = [1,2,3]
>>> id(t1)
8282220
>>> t1+=[4]
>>> t1
[1, 2, 3, 4]
>>> id(t1)
8282220
>>>

Why should the source container of a reference change the behavior of an
object?

>>> t = ([1],[2],[3])
>>> t1 = t[0]
>>> t1 += [22]
>>> t
([1, 22], [2], [3])
>>> t[0][0]+=[222]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +=
>>>

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list