copy on write

John O'Hagan research at johnohagan.com
Thu Feb 2 09:11:53 CET 2012


On Thu, 2 Feb 2012 01:34:48 -0500
Devin Jeanpierre <jeanpierreda at gmail.com> wrote:

> On Wed, Feb 1, 2012 at 10:18 PM, John O'Hagan
> <research at johnohagan.com> wrote:
> > On Fri, 13 Jan 2012 10:40:47 -0800
> > Ethan Furman <ethan at stoneleaf.us> wrote:
> >
> >> Steven D'Aprano wrote:
> >> > Normally this is harmless, but there is one interesting little
> >> > glitch you can get:
> >> >
> >> >>>> t = ('a', [23])
> >> >>>> t[1] += [42]
> >> > Traceback (most recent call last):
> >> >   File "<stdin>", line 1, in <module>
> >> > TypeError: 'tuple' object does not support item assignment
> >> >>>> t
> >> > ('a', [23, 42])
> >
> > IMHO, this is worthy of bug-hood: shouldn't we be able to conclude
> > from the TypeError that the assignment failed?
> 
> It did fail. The mutation did not.

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. I can't think of another example of (what appears to be but is not) a single operation failing with an exception, but still doing exactly what you intended.

> 
> I can't think of any way out of this misleadingness, although if you
> can that would be pretty awesome.

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. 

John






More information about the Python-list mailing list