copy — Shallow and deep copy operations

Source code: Lib/copy.py


Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations, and a function to create a modified copy of an object.

After an assignment, both names refer to the same list, so a change made through one name is visible through the other:

>>> colors = ['red', 'green']
>>> same_list = colors
>>> colors.append('blue')
>>> same_list
['red', 'green', 'blue']

To get a separate list, use copy.copy():

>>> import copy
>>> new_list = copy.copy(colors)
>>> colors.append('yellow')
>>> new_list
['red', 'green', 'blue']

copy.copy() makes a shallow copy: the new list is a separate object, but it contains the same items as the original. This matters when the items can themselves be changed:

>>> rows = [[1, 2], [3, 4]]
>>> shallow = copy.copy(rows)
>>> rows[0].append('new')
>>> shallow
[[1, 2, 'new'], [3, 4]]

To copy the inner lists as well, use copy.deepcopy():

>>> rows = [[1, 2], [3, 4]]
>>> deep = copy.deepcopy(rows)
>>> rows[0].append('new')
>>> deep
[[1, 2], [3, 4]]

Functions

copy.copy(obj)

Return a shallow copy of obj.

copy.deepcopy(obj, memo=None)

Return a deep copy of obj.

The memo dictionary records the objects already copied. It should only be passed by an __deepcopy__() method.

copy.replace(obj, /, **changes)

Return a new object of the same type as obj, replacing fields with values from changes.

This function is more limited than copy() and deepcopy(). It only supports named tuples created by namedtuple(), dataclasses, and other classes which define the __replace__() method. A TypeError is raised for other objects.

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> copy.replace(Point(1, 2), y=5)
Point(x=1, y=5)

Added in version 3.13.

exception copy.Error

Raised for module specific errors.

Shallow and deep copies

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Two problems often exist with deep copy operations that don’t exist with shallow copy operations:

  • Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.

  • Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.

The deepcopy() function avoids these problems by:

  • keeping a memo dictionary of objects already copied during the current copying pass; and

  • letting user-defined classes override the copying operation or the set of components copied.

This module does not copy types like module, stack trace, stack frame, file, socket, window, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module. Immutable built-in objects like numbers and strings are also returned unchanged.

Shallow copies of many collections can be made using the corresponding copy() method (such as list.copy(), dict.copy() or set.copy()), and of sequences (such as lists or bytearrays) by making a slice of the entire sequence (sequence[:]). However, these methods and slicing can create an instance of the base type when copying an instance of a subclass, whereas copy.copy() normally returns an instance of the same type.

Customizing copying

Classes can use the same interfaces to control copying that they use to control pickling. See the description of module pickle for information on these methods. In fact, the copy module uses the registered pickle functions from the copyreg module.

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__().

object.__copy__(self)

Called to implement the shallow copy operation; no additional arguments are passed.

object.__deepcopy__(self, memo)

Called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__ implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument. The memo dictionary should be treated as an opaque object.

In this example, a shallow copy of a Playlist gets its own list of songs, and a deep copy shares the library with the original:

import copy

class Playlist:
    def __init__(self, songs, library):
        self.songs = songs
        self.library = library

    def __copy__(self):
        return type(self)(list(self.songs), self.library)

    def __deepcopy__(self, memo):
        songs = copy.deepcopy(self.songs, memo)
        return type(self)(songs, self.library)
>>> library = {'Brave Sir Robin': 'robin.mp3'}
>>> original = Playlist(['Brave Sir Robin'], library)
>>> shallow = copy.copy(original)
>>> shallow.songs is original.songs
False
>>> deep = copy.deepcopy(original)
>>> deep.library is original.library
True

In order for a class to support copy.replace(), it can define the special method __replace__().

object.__replace__(self, /, **changes)

Called to implement copy.replace(). This method should create a new object of the same type, replacing fields with values from changes.

Added in version 3.13.

In this example, copy.replace() works for instances of Point:

import copy

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __replace__(self, /, **changes):
        fields = {'x': self.x, 'y': self.y} | changes
        return type(self)(**fields)
>>> point = copy.replace(Point(1, 2), y=5)
>>> point.x, point.y
(1, 5)

See also

Module pickle

Discussion of the special methods used to support object state retrieval and restoration.