Emiliano
Emiliano

Reputation: 23752

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)

Upvotes: 6

Views: 1017

Answers (3)

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

Upvotes: 6

Dan D.
Dan D.

Reputation: 74655

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

Upvotes: 4

robert
robert

Reputation: 34408

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.

Upvotes: 3

Related Questions