Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Lib/copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,10 @@ def deepcopy(x, memo=None):
if memo is None:
memo = {}
else:
y = memo.get(d, None)
if y is not None:
return y
try:
return memo[d]
except KeyError:
pass

copier = _deepcopy_dispatch.get(cls)
if copier is not None:
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,22 @@ def __eq__(self, other):
self.assertIsNot(y, x)
self.assertIsNot(y.foo, x.foo)

def test_deepcopy_inst_deepcopy_returns_none(self):
# gh-154594: the memo used to use None as its own "not cached"
# sentinel, so a __deepcopy__ that legitimately returns None was
# indistinguishable from a memo miss and got invoked again on
# every subsequent reference to the same object.
calls = []
class C:
def __deepcopy__(self, memo):
calls.append(1)
memo[id(self)] = None
return None
x = C()
y = copy.deepcopy([x, x, x])
self.assertEqual(y, [None, None, None])
self.assertEqual(len(calls), 1)

def test_deepcopy_inst_getinitargs(self):
class C:
def __init__(self, foo):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :func:`copy.deepcopy` re-invoking an object's :meth:`~object.__deepcopy__`
on every subsequent reference to that object when it returns :const:`None`.
The memo dict now distinguishes a cached ``None`` result from a cache miss.
Loading