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

Skip to content

Commit 101f09e

Browse files
committed
Issue #10323: Predictable final state for slice().
1 parent fdb32c1 commit 101f09e

3 files changed

Lines changed: 13 additions & 3 deletions

File tree

Lib/test/test_itertools.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,11 @@ def test_islice(self):
788788
self.assertRaises(ValueError, islice, range(10), 1, 'a', 1)
789789
self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
790790

791+
# Issue #10323: Less islice in a predictable state
792+
c = count()
793+
self.assertEqual(list(islice(c, 1, 3, 50)), [1])
794+
self.assertEqual(next(c), 3)
795+
791796
def test_takewhile(self):
792797
data = [1, 3, 5, 20, 2, 4, 6, 8]
793798
underten = lambda x: x<10

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ Core and Builtins
2828
Library
2929
-------
3030

31+
- Issue #10323: itertools.islice() now consumes the minimum number of
32+
inputs before stopping. Formerly, the final state of the underlying
33+
iterator was undefined.
34+
3135
- Issue #10565: The collections.Iterator ABC now checks for both
3236
__iter__ and __next__.
3337

Modules/itertoolsmodule.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1215,6 +1215,7 @@ islice_next(isliceobject *lz)
12151215
{
12161216
PyObject *item;
12171217
PyObject *it = lz->it;
1218+
Py_ssize_t stop = lz->stop;
12181219
Py_ssize_t oldnext;
12191220
PyObject *(*iternext)(PyObject *);
12201221

@@ -1226,16 +1227,16 @@ islice_next(isliceobject *lz)
12261227
Py_DECREF(item);
12271228
lz->cnt++;
12281229
}
1229-
if (lz->stop != -1 && lz->cnt >= lz->stop)
1230+
if (stop != -1 && lz->cnt >= stop)
12301231
return NULL;
12311232
item = iternext(it);
12321233
if (item == NULL)
12331234
return NULL;
12341235
lz->cnt++;
12351236
oldnext = lz->next;
12361237
lz->next += lz->step;
1237-
if (lz->next < oldnext) /* Check for overflow */
1238-
lz->next = lz->stop;
1238+
if (lz->next < oldnext || (stop != -1 && lz->next > stop))
1239+
lz->next = stop;
12391240
return item;
12401241
}
12411242

0 commit comments

Comments
 (0)