Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does deepcopy use copy-on-write?

I wonder if the python interpreter applies copy on write strategy when doing a deepcopy on mutable objects.

Also, I'd like to know if the deepcopy is performed also on nonmutable object (that would seem strange to me however)

like image 484
Emiliano Avatar asked Jul 25 '11 16:07

Emiliano


3 Answers

It does not do copy-on-write.

It doesn't do a deep copy on some built-in immutable types, but any user-defined "immutable" types will be deep-copied.

copy.py in the Python 2.7 standard library includes this message in its documentation:

This version does not copy types like module, class, function, method, nor stack trace, stack frame, nor file, socket, window, nor array, nor any similar types.

copy handles immutable objects like this:

def _copy_immutable(x):
    return x
for t in (type(None), int, long, float, bool, str, tuple,
          frozenset, type, xrange, types.ClassType,
          types.BuiltinFunctionType, type(Ellipsis),
          types.FunctionType, weakref.ref):
    d[t] = _copy_immutable
for name in ("ComplexType", "UnicodeType", "CodeType"):
    t = getattr(types, name, None)
    if t is not None:
        d[t] = _copy_immutable

deepcopy uses a more complicated scheme that's too long to copy into this most, but the gist is the same. One interesting point is that _deepcopy_tuple iterates through its elements and don't create a new object until it finds an element that was copied.

for i in range(len(x)):
    if x[i] is not y[i]:
        y = tuple(y)
        break
else:
    y = x
like image 54
Jeremy Avatar answered Nov 15 '22 04:11

Jeremy


No, it doesn't it, just copies the objects. And it also must copy immutable objects if they reference mutables.

like image 28
Dan D. Avatar answered Nov 15 '22 04:11

Dan D.


Let's see:

>>> import copy
>>> x = [[1],[2],"abc"]
>>> y = copy.deepcopy(x)
>>> id(x[0])
4299612960
>>> id(y[0])
4299541608
>>> id(x[2])
4297774504
>>> id(y[2])
4297774504

For the first element of x and y, the copy is performed and the object has a new id. The third element, an immutable string, is not copied.

like image 45
robert Avatar answered Nov 15 '22 03:11

robert