ZetCode

Python __deepcopy__ Method

Last modified November 17, 2026 Python 3.15

copy.deepcopy() creates a new object and recursively copies everything reachable from it. For classes with internal structure, the default algorithm may be wrong: it may copy objects that should stay shared, or it may not know how to rebuild a type that has no ordinary constructor. The __deepcopy__ hook takes over that work. This article explains the memo dictionary, the order of operations for cyclic data, and the patterns that keep a deep copy consistent.

The default deep copy

Without a hook, copy.deepcopy() recreates each object by walking its attributes, using the reduction protocol where necessary. Nested lists, dictionaries, and custom instances are duplicated at every level, so changing a value in the copy leaves the original untouched.

default_deepcopy.py
import copy


class Report:
    def __init__(self, title, rows):
        self.title = title
        self.rows = rows


report = Report("Sales", [[1, 2], [3, 4]])
duplicate = copy.deepcopy(report)

print(report is duplicate)
print(report.rows is duplicate.rows)
print(report.rows[0] is duplicate.rows[0])

duplicate.rows[0][0] = 99
print(report.rows)
print(duplicate.rows)

Both the report and its row list are new objects, and the inner rows are new as well. The assignment to duplicate.rows[0][0] is therefore invisible in the original. This is the behaviour to expect whenever a class has no custom deep-copy logic and its attributes are picklable or reducible.

$ python default_deepcopy.py
False
False
False
[[1, 2], [3, 4]]
[[99, 2], [3, 4]]

Implementing __deepcopy__

The hook receives the object and the memo dictionary, and returns a new object. The memo maps id(original) to the copy, which lets later recursive calls reuse an object that has already been duplicated. The example registers the new Grid before copying its rows and passes the same memo to the nested call.

basic_deepcopy.py
import copy


class Grid:
    def __init__(self, rows):
        self.rows = rows

    def __deepcopy__(self, memo):
        new = Grid([])
        memo[id(self)] = new
        new.rows = copy.deepcopy(self.rows, memo)
        return new

    def __repr__(self):
        return f"Grid({self.rows!r})"


grid = Grid([[1, 2], [3, 4]])
duplicate = copy.deepcopy(grid)

duplicate.rows[0][0] = 99

print(grid)
print(duplicate)
print(duplicate.rows is grid.rows)
print(duplicate.rows[0] is grid.rows[0])

The two grids have separate row lists and separate inner lists, so editing the copy changes only the copy. The memo entry is not strictly needed for this acyclic example, but it becomes essential as soon as an attribute refers back to the object. Passing memo down also preserves sharing among nested objects, which the next sections show.

$ python basic_deepcopy.py
Grid([[1, 2], [3, 4]])
Grid([[99, 2], [3, 4]])
False
False

Why the memo entry comes first

A cycle is a structure that refers back to itself, such as two nodes pointing at each other. If the hook recurses into next before recording the copy, the recursion never reaches a base case. The following version stores the memo entry after the recursive call and fails with RecursionError.

bad_cycle.py
import copy


class BadNode:
    def __init__(self, value):
        self.value = value
        self.next = None

    def __deepcopy__(self, memo):
        new = BadNode(copy.deepcopy(self.value, memo))
        new.next = copy.deepcopy(self.next, memo)
        memo[id(self)] = new
        return new


a = BadNode("a")
b = BadNode("b")
a.next = b
b.next = a

try:
    copy.deepcopy(a)
except RecursionError as e:
    print(type(e).__name__, e)

Copying a recurses into b, which recurses back into a, because neither object is in the memo yet. The exception is caught so the script ends cleanly, but in real code the failure aborts the copy and leaves a partially built object graph behind.

$ python bad_cycle.py
RecursionError maximum recursion depth exceeded

A correct cyclic copy

The corrected version records the new node before touching next. When the recursion returns to a, the memo already holds the copy, so the cycle is closed with a reference to that copy instead of another recursive call.

cycle.py
import copy


class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

    def __deepcopy__(self, memo):
        new = Node(copy.deepcopy(self.value, memo))
        memo[id(self)] = new
        new.next = copy.deepcopy(self.next, memo)
        return new

    def __repr__(self):
        return f"Node({self.value!r})"


a = Node("a")
b = Node("b")
a.next = b
b.next = a

duplicate = copy.deepcopy(a)

print(duplicate)
print(duplicate.next)
print(duplicate.next.next is duplicate)
print(duplicate is a)

The copy has the same two values, and duplicate.next.next is the copy itself, so the cycle is reproduced rather than flattened or duplicated infinitely. The original graph is untouched. This order — create, memoize, then recurse — is the rule for every custom deep copy that might meet a cycle.

$ python cycle.py
Node('a')
Node('b')
True
False

Preserving shared references

The memo is not only for cycles. When the same object is reachable through two paths, a deep copy should produce one shared copy, not two independent ones. copy.deepcopy() checks the memo for every object, so the alias relationship survives the copy.

shared_refs.py
import copy

shared = [1, 2]
data = {"first": shared, "second": shared}
duplicate = copy.deepcopy(data)

print(duplicate["first"] is duplicate["second"])
print(duplicate["first"] is shared)
duplicate["first"].append(3)
print(data["second"])
print(duplicate["second"])

text = "immutable"
print(copy.deepcopy(text) is text)

Both keys of the copy point to one new list, which is different from the original list. Appending through the first key is visible through the second, but not in the source dictionary. The last line shows that immutable values such as strings are returned unchanged, because duplicating them would serve no purpose.

$ python shared_refs.py
True
False
[1, 2]
[1, 2, 3]
True

Subclasses and generic attribute copying

A hard-coded constructor call in __deepcopy__ breaks for subclasses with additional arguments. A more general approach creates the instance with cls.__new__(cls), registers it in the memo, and then copies every entry of __dict__. The subclass keeps its type and its extra attributes without needing its own hook.

generic_deepcopy.py
import copy


class Shape:
    def __init__(self, name, points):
        self.name = name
        self.points = points

    def __deepcopy__(self, memo):
        cls = type(self)
        new = cls.__new__(cls)
        memo[id(self)] = new
        for key, value in self.__dict__.items():
            setattr(new, key, copy.deepcopy(value, memo))
        return new

    def __repr__(self):
        return f"{type(self).__name__}({self.name!r}, {self.points!r})"


class Polygon(Shape):
    def __init__(self, name, points, closed):
        super().__init__(name, points)
        self.closed = closed


polygon = Polygon("triangle", [(0, 0), (1, 0), (0, 1)], True)
duplicate = copy.deepcopy(polygon)

duplicate.points.append((1, 1))
duplicate.closed = False

print(polygon)
print(duplicate)
print(type(duplicate).__name__)
print(duplicate.points is polygon.points)

The duplicate is a Polygon, not a plain Shape, and it has its own list of points. __new__ bypasses __init__, which is deliberate: the copied attributes already carry the state, and calling the constructor again could reset or revalidate it. Classes with __slots__ need to iterate over the slot names instead of __dict__.

$ python generic_deepcopy.py
Polygon('triangle', [(0, 0), (1, 0), (0, 1)])
Polygon('triangle', [(0, 0), (1, 0), (0, 1), (1, 1)])
Polygon
False

Best practices

A deep copy must reproduce the whole object graph, so treat the memo as part of the algorithm:

Source

copy.deepcopy - Python documentation

object.__deepcopy__ - Python documentation

copy - Python documentation

In this article we have implemented the __deepcopy__ method. We have covered the default recursive copy, the role of the memo dictionary, the order required for cyclic graphs, preservation of shared references, and a generic pattern for subclasses. For related topics, see Python __copy__ method, Python copy by value and by reference, Python __reduce__ method, and Python __del__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.