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

Gustavo Cordova gcordova at hebmex.com
Mon Jun 3 18:47:52 EDT 2002


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

The thing is that += MUST work also for immutable objects,
as well as mutables. So, it does a rebind of the final
value obtained --which in a list or dictionary, being mutable,
is the same as the initial reference, but in the case of
immutable objects, it's a different one than before--.

BUT, since it's trying to rebind a tuple's item, and it's
not allowed, an exception is raised; this is correct
behaviour.

So, it's not actually a bug, but an artifact of the hoops
Python needs to jump through in order to maintain total
dynamism in data types.

Instead of this:

   a = ([1],[2],[3])
   a[0] += [3]

do this:

   a = ([1],[2],[3])
   t = a[0]
   t += [3]

there won't be any exception, because 't' *can* be rebinded
to the value emmited by the += operation; *and* 'a' will
also contain the same reference.

It's not *totally* equivalent, because it's missing a
single, last step:

   a[0] = t

*that* is what's raising the exception, which is what
the += operator is trying to do in you're original version.

Happy hunting :-)

-gustavo





More information about the Python-list mailing list