[Python-checkins] r73401 - in python/trunk/Lib: collections.py test/test_collections.py

alexandre.vassalotti python-checkins at python.org
Fri Jun 12 23:52:14 CEST 2009


Author: alexandre.vassalotti
Date: Fri Jun 12 23:52:14 2009
New Revision: 73401

Log:
Make pickling of OrderedDict instances more efficient.


Modified:
   python/trunk/Lib/collections.py
   python/trunk/Lib/test/test_collections.py

Modified: python/trunk/Lib/collections.py
==============================================================================
--- python/trunk/Lib/collections.py	(original)
+++ python/trunk/Lib/collections.py	Fri Jun 12 23:52:14 2009
@@ -99,14 +99,16 @@
 
     def __reduce__(self):
         'Return state information for pickling'
-        items = [[k, self[k]] for k in self]
+        dictitems = self.iteritems()
         tmp = self.__map, self.__root
         del self.__map, self.__root
         inst_dict = vars(self).copy()
         self.__map, self.__root = tmp
-        if inst_dict:
-            return (self.__class__, (items,), inst_dict)
-        return self.__class__, (items,)
+        # Set the state item to None when the dictionary is empty. This saves
+        # about 2 opcodes when the object is pickled.
+        if not inst_dict:
+            inst_dict = None
+        return (self.__class__, (), inst_dict, None, dictitems)
 
     setdefault = MutableMapping.setdefault
     update = MutableMapping.update

Modified: python/trunk/Lib/test/test_collections.py
==============================================================================
--- python/trunk/Lib/test/test_collections.py	(original)
+++ python/trunk/Lib/test/test_collections.py	Fri Jun 12 23:52:14 2009
@@ -795,9 +795,9 @@
         # do not save instance dictionary if not needed
         pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
         od = OrderedDict(pairs)
-        self.assertEqual(len(od.__reduce__()), 2)
         od.x = 10
-        self.assertEqual(len(od.__reduce__()), 3)
+        self.assertGreaterEqual(len(od.__reduce__()), 2)
+        self.assertLessEqual(len(od.__reduce__()), 5)
 
     def test_repr(self):
         od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])


More information about the Python-checkins mailing list