Issue #10323: Predictable final state for slice().
authorRaymond Hettinger <python@rcn.com>
Tue, 30 Nov 2010 02:49:29 +0000 (02:49 +0000)
committerRaymond Hettinger <python@rcn.com>
Tue, 30 Nov 2010 02:49:29 +0000 (02:49 +0000)
Lib/test/test_itertools.py
Misc/NEWS
Modules/itertoolsmodule.c

index 06777a1ea61db79cbcaec8880f422c8d0f7cdd2a..fe6131abfed38c3fd42657902f2f48222c2d5a19 100644 (file)
@@ -788,6 +788,11 @@ class TestBasicOps(unittest.TestCase):
         self.assertRaises(ValueError, islice, range(10), 1, 'a', 1)
         self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
 
+        # Issue #10323:  Less islice in a predictable state
+        c = count()
+        self.assertEqual(list(islice(c, 1, 3, 50)), [1])
+        self.assertEqual(next(c), 3)
+
     def test_takewhile(self):
         data = [1, 3, 5, 20, 2, 4, 6, 8]
         underten = lambda x: x<10
index 71cbc3267e72105b0f33c8ad83d6701b48fa4fc1..320aaaa4a897711be5e7c0f55f612b3a1a4cec14 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -43,6 +43,10 @@ Core and Builtins
 Library
 -------
 
+- Issue #10323: itertools.islice() now consumes the minimum number of
+  inputs before stopping.  Formerly, the final state of the underlying
+  iterator was undefined.
+
 - Issue #10565: The collections.Iterator ABC now checks for both
   __iter__ and __next__.
 
index ba8d6dfde3d218b6c6af930c81b567b416abb9b1..d5336f24294df40c8f08d63f22cd5ff02f5628eb 100644 (file)
@@ -1215,6 +1215,7 @@ islice_next(isliceobject *lz)
 {
     PyObject *item;
     PyObject *it = lz->it;
+    Py_ssize_t stop = lz->stop;
     Py_ssize_t oldnext;
     PyObject *(*iternext)(PyObject *);
 
@@ -1226,7 +1227,7 @@ islice_next(isliceobject *lz)
         Py_DECREF(item);
         lz->cnt++;
     }
-    if (lz->stop != -1 && lz->cnt >= lz->stop)
+    if (stop != -1 && lz->cnt >= stop)
         return NULL;
     item = iternext(it);
     if (item == NULL)
@@ -1234,8 +1235,8 @@ islice_next(isliceobject *lz)
     lz->cnt++;
     oldnext = lz->next;
     lz->next += lz->step;
-    if (lz->next < oldnext)     /* Check for overflow */
-        lz->next = lz->stop;
+    if (lz->next < oldnext || (stop != -1 && lz->next > stop))
+        lz->next = stop;
     return item;
 }