copy on write

John O'Hagan research at
Thu Feb 2 22:08:06 EST 2012

On Thu, 02 Feb 2012 12:25:00 -0500
Terry Reedy <tjreedy at> wrote:

> On 2/2/2012 9:17 AM, John O'Hagan wrote:
> > It's not so much about the type of x but that of x[1]. Wouldn't it
> > be possible to omit the assignment simply if the object referred to
> > by x[1] uses "+=" without creating a new object? That way,
> > some_tuple[i] += y will succeed if some_tuple[i] is a list but not
> > with, say, an int. That seems reasonable to me.
> There was considerable discussion of the exact semantics of augmented 
> operations when they were introduced. I do not remember if that 
> particular idea was suggested (and rejected) or not. You could try to 
> look at the PEP, if there is one, or the dicussion ( probably on
> pydev list).

I think we're 12 years late on this one. It's PEP 203 from 2000 and the key phrase was:

"The in-place function should always return a new reference, either
to the old `x' object if the operation was indeed performed
in-place, or to a new object."

If this had read:

"The in-place function should return a reference to a new object
if the operation was not performed in-place."

or something like that, we wouldn't be discussing this.

The discussion on py-dev at the time was quite limited but there was some lively debate on this list the following year (in the context of widespread controversy over new-fangled features which also included list comprehensions and generators), to which the BDFL's response was:

"You shouldn't think "+= is confusing because sometimes it modifies an
object and sometimes it does".  Gee, there are lots of places where
something that's *spelled* the same has a different effect depending
on the object types involved."

That's true, but I don't think there should be a different effect depending on what _name_ we use for an operand:

>>> t=([],)
>>> l=t[0]
>>> l is t[0]
>>> l+=[1]
>>> t
>>> t[0]+=[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
([1, 1],)
>>> l is t[0]

Same object, same operator, different name, different outcome. Maybe that was obvious from the foregoing discussion, but it shocked me when put that way.


More information about the Python-list mailing list