diff -r e3217efa6edd Lib/test/test_itertools.py --- a/Lib/test/test_itertools.py Sat Apr 19 13:24:03 2014 -0700 +++ b/Lib/test/test_itertools.py Mon Apr 28 23:07:19 2014 +0400 @@ -792,6 +792,15 @@ self.assertEqual(list(islice(c, 1, 3, 50)), [1]) self.assertEqual(next(c), 3) + # Issue #21321: check source iterator is not referenced + # from islice() after the latter has been exhausted + a = [random.random() for i in range(10)] + before = sys.getrefcount(a) + b = islice(a, 5) + for i in b: pass + after = sys.getrefcount(a) + self.assertEqual(before, after) + def test_takewhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] underten = lambda x: x<10 diff -r e3217efa6edd Modules/itertoolsmodule.c --- a/Modules/itertoolsmodule.c Sat Apr 19 13:24:03 2014 -0700 +++ b/Modules/itertoolsmodule.c Mon Apr 28 23:07:19 2014 +0400 @@ -1241,19 +1241,22 @@ Py_ssize_t oldnext; PyObject *(*iternext)(PyObject *); + if (it == NULL) + return NULL; + iternext = *Py_TYPE(it)->tp_iternext; while (lz->cnt < lz->next) { item = iternext(it); if (item == NULL) - return NULL; + goto empty; Py_DECREF(item); lz->cnt++; } if (stop != -1 && lz->cnt >= stop) - return NULL; + goto empty; item = iternext(it); if (item == NULL) - return NULL; + goto empty; lz->cnt++; oldnext = lz->next; /* The (size_t) cast below avoids the danger of undefined @@ -1262,6 +1265,10 @@ if (lz->next < oldnext || (stop != -1 && lz->next > stop)) lz->next = stop; return item; + +empty: + Py_CLEAR(lz->it); + return NULL; } PyDoc_STRVAR(islice_doc,