Search code examples
pythondeep-copycopy-on-write

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)


Solution

  • 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