diff --git a/Lib/copy.py b/Lib/copy.py index bbbd5b3313c..c227a2e5c7c 100644 --- a/Lib/copy.py +++ b/Lib/copy.py @@ -328,17 +328,7 @@ def _reconstruct(x, info, deep, memo=None): args = deepcopy(args, memo) y = callable(*args) memo[id(x)] = y - if listiter is not None: - for item in listiter: - if deep: - item = deepcopy(item, memo) - y.append(item) - if dictiter is not None: - for key, value in dictiter: - if deep: - key = deepcopy(key, memo) - value = deepcopy(value, memo) - y[key] = value + if state: if deep: state = deepcopy(state, memo) @@ -354,6 +344,18 @@ def _reconstruct(x, info, deep, memo=None): if slotstate is not None: for key, value in slotstate.iteritems(): setattr(y, key, value) + + if listiter is not None: + for item in listiter: + if deep: + item = deepcopy(item, memo) + y.append(item) + if dictiter is not None: + for key, value in dictiter: + if deep: + key = deepcopy(key, memo) + value = deepcopy(value, memo) + y[key] = value return y del d @@ -416,6 +418,16 @@ def _test(): print map(repr.repr, l1) print map(repr.repr, l2) print map(repr.repr, l3) + class odict(dict): + def __init__(self, d = {}): + self.a = 99 + dict.__init__(self, d) + def __setitem__(self, k, i): + dict.__setitem__(self, k, i) + self.a + o = odict({"A" : "B"}) + x = deepcopy(o) + print(o, x) if __name__ == '__main__': _test() diff --git a/Lib/test/test_copy.py b/Lib/test/test_copy.py index e3503c43433..6b64f10112e 100644 --- a/Lib/test/test_copy.py +++ b/Lib/test/test_copy.py @@ -526,6 +526,26 @@ class TestCopy(unittest.TestCase): self.assertEqual(x.foo, y.foo) self.assertTrue(x.foo is not y.foo) + def test_deepcopy_dict_subclass(self): + class C(dict): + def __init__(self, d=None): + if not d: + d = {} + self._keys = list(d.keys()) + dict.__init__(self, d) + def __setitem__(self, key, item): + dict.__setitem__(self, key, item) + if key not in self._keys: + self._keys.append(key) + x = C(d={'foo':0}) + y = copy.deepcopy(x) + self.assertEqual(x, y) + self.assertEqual(x._keys, y._keys) + self.assertTrue(x is not y) + x['bar'] = 1 + self.assertNotEqual(x, y) + self.assertNotEqual(x._keys, y._keys) + def test_copy_list_subclass(self): class C(list): pass diff --git a/Misc/ACKS b/Misc/ACKS index 293188c1787..1fa27d437e6 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -472,7 +472,7 @@ Ross Light Shawn Ligocki Martin Ligr Christopher Lindblad -Bjorn Lindqvist +Björn Lindqvist Per Lindqvist Eric Lindvall Gregor Lingl diff --git a/Misc/NEWS b/Misc/NEWS index 914c5f1bf00..8ac6168da5c 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -36,6 +36,9 @@ Core and Builtins Library ------- +- Issue #1100562: Fix deep-copying of objects derived from the list and + dict types. Patch by Michele Orrù and Björn Lindqvist. + - Issue #7005: Fixed output of None values for RawConfigParser.write and ConfigParser.write.