copy on write

Wolfram Hinderer wolfram.hinderer at googlemail.com
Sun Feb 5 09:09:50 EST 2012


On 3 Feb., 11:47, John O'Hagan <resea... at johnohagan.com> wrote:

> But isn't it equally true if we say that z = t[1], then t[1] += x is syntactic sugar for z = z.__iadd__(x)? Why should that fail, if z can handle it?

It's more like syntactic sugar for
y = t; z = y.__getitem__(1); z.__iadd__(x); y.__setitem__(1, z)

It's clear that only the last expression fails, after the mutation has
taken place.

Just in case you wonder about the y: you need it for more complicated
cases.
t[1][1] += [4] is syntactic sugar for
y = t.__getitem__(1); z = y.__getitem__(1); z.__iadd__([4]);
y.__setitem__(1, z)

That makes clear why there's no exception in this code:
>>> t = (0, [1, [2, 3]])
>>> t[1][1] += [4]
>>> t
(0, [1, [2, 3, 4]])




More information about the Python-list mailing list