Behavior of += (was Re: [Python-Dev] Customization docs)
huaiyu at gauss.almadan.ibm.com
Wed Jun 5 03:19:44 CEST 2002
John Roth <johnroth at ameritech.net> wrote:
>The assignment occurs because the pointer to the list has to
>be changed to point to the (possibly) new location of the list
>in memory. In other words, the second element of the tuple
>has to be rebound.
>There is no way of avoiding this, since objects are known
>internally by their location in memory, and if you change the
>object, you may (not necessarilly will) change that object's
>location. Therefore, the pointer to the object must also be
>changed in this instance. That is what causes the exception.
I don't think objects are pointers to memory locations.
>>> a = [1,2,3]
>>> b = a = ['a','b','c']
>>> a += ['d']
['a', 'b', 'c', 'd']
This also works when the list is of an appropriate size that appending
actually reallocates memory and do a copy.
Objects are referenced by their ids (or equivalent). Their memory location
may or may not change when it is modified, but if it is the same object,
every name that was refering to it will remain referencing to it after the
modification, regardless of its memory location.
The operations of a+=b for immutable objects is of a completely different
nature. If creates a different object (a+b) and rebinds the name 'a' to it.
If any other names were bound to the object that was named 'a', they will
not feel the effect that 'a' is now pointing to a different object. They
will remain bound to the old object.
More information about the Python-list