]> granicus.if.org Git - python/commitdiff
SF 1191699: Make slices picklable
authorRaymond Hettinger <python@rcn.com>
Wed, 11 Apr 2007 18:40:58 +0000 (18:40 +0000)
committerRaymond Hettinger <python@rcn.com>
Wed, 11 Apr 2007 18:40:58 +0000 (18:40 +0000)
Lib/test/test_slice.py
Misc/NEWS
Objects/sliceobject.c

index c34d9ea4ad393a7992d74d2a07a09668ae89f535..83f051f688894b50ce9110f437fd691c7f8051b1 100644 (file)
@@ -2,6 +2,7 @@
 
 import unittest
 from test import test_support
+from cPickle import loads, dumps
 
 import sys
 
@@ -102,6 +103,13 @@ class SliceTest(unittest.TestCase):
         x[1:2] = 42
         self.assertEquals(tmp, [(1, 2, 42)])
 
+    def test_pickle(self):
+        s = slice(10, 20, 3)
+        for protocol in (0,1,2):
+            t = loads(dumps(s, protocol))
+            self.assertEqual(s, t)
+            self.assertEqual(s.indices(15), t.indices(15))
+            self.assertNotEqual(id(s), id(t))
 
 def test_main():
     test_support.run_unittest(SliceTest)
index d15f673275c312d4df5057f7646cde49cac0c82a..96b8b1d8cbec1d5f26ede3e36182a1bd6e424487 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,8 @@ What's New in Python 2.6 alpha 1?
 Core and builtins
 -----------------
 
+- Request #1191699:  Slices can now be pickled.
+
 - Patch #1682205: a TypeError while unpacking an iterable is no longer
   masked by a generic one with the message "unpack non-sequence".
 
index d8a24653a7d77b1176a8f3bf37eb9c13c4a87a33..3fb1430308351df3f0fa51dc120feabca6d3d5db 100644 (file)
@@ -274,9 +274,19 @@ indices, and the stride length of the extended slice described by\n\
 S. Out of bounds indices are clipped in a manner consistent with the\n\
 handling of normal slices.");
 
+static PyObject *
+slice_reduce(PySliceObject* self)
+{
+       return Py_BuildValue("O(OOO)", self->ob_type, self->start, self->stop, self->step);
+}
+
+PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
+
 static PyMethodDef slice_methods[] = {
        {"indices",     (PyCFunction)slice_indices,
         METH_O,        slice_indices_doc},
+       {"__reduce__",  (PyCFunction)slice_reduce,
+        METH_NOARGS,   reduce_doc},
        {NULL, NULL}
 };