[Python-checkins] cpython: don't memoize objects that are their own copies (closes #12422)

benjamin.peterson python-checkins at python.org
Mon Jun 27 23:22:57 CEST 2011


http://hg.python.org/cpython/rev/e24ad85e9608
changeset: 71018:e24ad85e9608
user: Benjamin Peterson <benjamin at python.org>
date: Mon Jun 27 16:22:46 2011 -0500
summary:
 don't memoize objects that are their own copies (closes #12422)
Patch mostly by Alex Gaynor.
files:
 Lib/copy.py | 12 +++++++-----
 Lib/test/test_copy.py | 19 +++++++++++++++++--
 Misc/NEWS | 3 +++
 3 files changed, 27 insertions(+), 7 deletions(-)
diff --git a/Lib/copy.py b/Lib/copy.py
--- a/Lib/copy.py
+++ b/Lib/copy.py
@@ -173,8 +173,10 @@
 "un(deep)copyable object of type %s" % cls)
 y = _reconstruct(x, rv, 1, memo)
 
- memo[d] = y
- _keep_alive(x, memo) # Make sure x lives at least as long as d
+ # If is its own copy, don't memoize.
+ if y is not x:
+ memo[d] = y
+ _keep_alive(x, memo) # Make sure x lives at least as long as d
 return y
 
 _deepcopy_dispatch = d = {}
@@ -214,9 +216,10 @@
 y = []
 for a in x:
 y.append(deepcopy(a, memo))
- d = id(x)
+ # We're not going to put the tuple in the memo, but it's still important we
+ # check for it, in case the tuple contains recursive mutable structures.
 try:
- return memo[d]
+ return memo[id(x)]
 except KeyError:
 pass
 for i in range(len(x)):
@@ -225,7 +228,6 @@
 break
 else:
 y = x
- memo[d] = y
 return y
 d[tuple] = _deepcopy_tuple
 
diff --git a/Lib/test/test_copy.py b/Lib/test/test_copy.py
--- a/Lib/test/test_copy.py
+++ b/Lib/test/test_copy.py
@@ -321,9 +321,24 @@
 
 def test_deepcopy_keepalive(self):
 memo = {}
- x = 42
+ x = []
 y = copy.deepcopy(x, memo)
- self.assertTrue(memo[id(x)] is x)
+ self.assertIs(memo[id(memo)][0], x)
+
+ def test_deepcopy_dont_memo_immutable(self):
+ memo = {}
+ x = [1, 2, 3, 4]
+ y = copy.deepcopy(x, memo)
+ self.assertEqual(y, x)
+ # There's the entry for the new list, and the keep alive.
+ self.assertEqual(len(memo), 2)
+
+ memo = {}
+ x = [(1, 2)]
+ y = copy.deepcopy(x, memo)
+ self.assertEqual(y, x)
+ # Tuples with immutable contents are immutable for deepcopy.
+ self.assertEqual(len(memo), 2)
 
 def test_deepcopy_inst_vanilla(self):
 class C:
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -200,6 +200,9 @@
 Library
 -------
 
+- Issue #12422: In the copy module, don't store objects that are their own copy
+ in the memo dict.
+
 - Issue #12303: Add sigwaitinfo() and sigtimedwait() to the signal module.
 
 - Issue #12404: Remove C89 incompatible code from mmap module. Patch by Akira
-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /