copy on write

John O'Hagan research at
Thu Feb 2 09:17:48 EST 2012

On 02 Feb 2012 09:16:40 GMT
Steven D'Aprano <steve+comp.lang.python at> wrote:

> On Thu, 02 Feb 2012 19:11:53 +1100, John O'Hagan wrote:
> > You're right, in fact, for me the surprise is that "t[1] +=" is
> > interpreted as an assignment at all, given that for lists (and other
> > mutable objects which use "+=") it is a mutation. Although as Steven
> > says elsewhere, it actually is an assignment, but one which ends up
> > reassigning to the same object.
> >  
> > But it shouldn't be both.
> Do you expect that x += 1 should succeed? After all, "increment and 
> decrement numbers" is practically THE use-case for the augmented 
> assignment operators.
> How can you expect x += 1 to succeed without an assignment? 

I don't; obviously, for immutable objects assignment is the only possibility.

> Perhaps you are thinking that Python could determine ahead of time 
> whether x[1] += y involved a list or a tuple, and not perform the
> finally assignment if x was a tuple. Well, maybe, but such an
> approach (if possible!) is fraught with danger and mysterious errors
> even harder to debug than the current situation. And besides, what
> should Python do about non-built-in types? There is no way in general
> to predict whether x[1] = something will succeed except to actually
> try it.

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.


> > 
> > In the case above, the failure of the assignment is of no
> > consequence. I think it would make more sense if applying "+=" to a
> > tuple element were treated (by the interpreter I suppose) only on
> > the merits of the element, and not as an assignment to the tuple.
> How should the interpreter deal with other objects which happen to
> raise TypeError? By always ignoring it?
> x = [1, None, 3]
> x[1] += 2  # apparently succeeds
> Or perhaps by hard-coding tuples and only ignoring errors for tuples?
> So now you disguise one error but not others?

I'm not suggesting either of those. None can't be modified in place. But for objects which can, wouldn't omitting the final assignment prevent the TypeError in the first place?


More information about the Python-list mailing list