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
6 changes: 4 additions & 2 deletions Lib/copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ class Error(Exception):

__all__ = ["Error", "copy", "deepcopy", "replace"]

_MEMO_MISS = object()

def copy(x):
"""Shallow copy operation on arbitrary Python objects.

Expand Down Expand Up @@ -122,8 +124,8 @@ def deepcopy(x, memo=None):
if memo is None:
memo = {}
else:
y = memo.get(d, None)
if y is not None:
y = memo.get(d, _MEMO_MISS)
if y is not _MEMO_MISS:
return y

copier = _deepcopy_dispatch.get(cls)
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,19 @@ def m(self):
self.assertIs(g.b.__self__, g)
g.b()

def test_deepcopy_memo_none_result(self):
# Objects whose deepcopy result is None must still be memoized.
call_count = 0
class C:
def __deepcopy__(self, memo):
nonlocal call_count
call_count += 1
memo[id(self)] = None
return None
obj = C()
copy.deepcopy([obj, obj, obj])
self.assertEqual(call_count, 1)


class TestReplace(unittest.TestCase):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :func:`copy.deepcopy` memo lookup using ``None`` as the miss sentinel,
which prevented memoization of objects whose deep copy result is ``None``.
Use a private sentinel object instead. Patch by tonghuaroot.
Loading