copy on write

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jan 13 07:10:45 EST 2012


On Fri, 13 Jan 2012 11:33:24 +0000, Eduardo Suarez-Santana wrote:

> I wonder whether this is normal behaviour.
> 
> I would expect equal sign to copy values from right to left. 

Assignment in Python never copies values.

> However, it
> seems there is a copy-on-write mechanism that is not working.

There is no copy-on-write.

Assignment in Python is name binding: the name on the left hand side is 
bound to the object on the right. An object can have zero, one or many 
names. If the object is mutable, changes to the object will be visible 
via any name:

>>> x = []  # lists are mutable objects
>>> y = x  # not a copy of x, but x and y point to the same object
>>> x.append(42)  # mutates the object in place
>>> print y
[42]

The same rules apply not just to names, but also to list items and dict 
items, as well as attributes, and any other reference:

>>> z = [x, y]  # z is a list containing the same sublist twice
>>> z[0].append(23)
>>> print z
[[42, 23], [42, 23]]

When you work with floats, ints or strings, you don't notice this because 
those types are immutable: you can't modify those objects in place. So 
for example:

>>> a = 42  # binds the name 'a' to the object 42
>>> b = a  # a and b point to the same object
>>> a += 1  # creates a new object, and binds it to a
>>> print b  # leaving b still pointing to the old object
42


-- 
Steven



More information about the Python-list mailing list