Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3ee6dab

Browse files
Issue #17900: Allowed pickling of recursive OrderedDicts. Decreased pickled
size and pickling time.
1 parent b10c71d commit 3ee6dab

3 files changed

Lines changed: 15 additions & 6 deletions

File tree

Lib/collections/__init__.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -199,13 +199,10 @@ def __repr__(self):
199199

200200
def __reduce__(self):
201201
'Return state information for pickling'
202-
items = [[k, self[k]] for k in self]
203202
inst_dict = vars(self).copy()
204203
for k in vars(OrderedDict()):
205204
inst_dict.pop(k, None)
206-
if inst_dict:
207-
return (self.__class__, (items,), inst_dict)
208-
return self.__class__, (items,)
205+
return self.__class__, (), inst_dict or None, None, iter(self.items())
209206

210207
def copy(self):
211208
'od.copy() -> a shallow copy of od'

Lib/test/test_collections.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1245,9 +1245,18 @@ def test_reduce_not_too_fat(self):
12451245
# do not save instance dictionary if not needed
12461246
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
12471247
od = OrderedDict(pairs)
1248-
self.assertEqual(len(od.__reduce__()), 2)
1248+
self.assertIsNone(od.__reduce__()[2])
12491249
od.x = 10
1250-
self.assertEqual(len(od.__reduce__()), 3)
1250+
self.assertIsNotNone(od.__reduce__()[2])
1251+
1252+
def test_pickle_recursive(self):
1253+
od = OrderedDict()
1254+
od[1] = od
1255+
for proto in range(-1, pickle.HIGHEST_PROTOCOL + 1):
1256+
dup = pickle.loads(pickle.dumps(od, proto))
1257+
self.assertIsNot(dup, od)
1258+
self.assertEqual(list(dup.keys()), [1])
1259+
self.assertIs(dup[1], dup)
12511260

12521261
def test_repr(self):
12531262
od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,9 @@ Core and Builtins
9999
Library
100100
-------
101101

102+
- Issue #17900: Allowed pickling of recursive OrderedDicts. Decreased pickled
103+
size and pickling time.
104+
102105
- Issue #17914: Add os.cpu_count(). Patch by Yogesh Chaudhari, based on an
103106
initial patch by Trent Nelson.
104107

0 commit comments

Comments
 (0)