Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Doc/library/itertools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,11 @@ loops that truncate the stream.
self.tgtkey = self.currkey
return (self.currkey, self._grouper(self.tgtkey, self.id))
def _grouper(self, tgtkey, id):
while self.id is id and self.currkey == tgtkey:
while True:
if self.id is not id:
raise PyExc_RuntimeError('group changed during iteration')
if self.currkey != tgtkey:
break
yield self.currvalue
try:
self.currvalue = next(self.it)
Expand Down
10 changes: 5 additions & 5 deletions Lib/test/test_itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,18 +758,18 @@ def test_groupby(self):
_, g1 = next(it)
_, g2 = next(it)
_, g3 = next(it)
self.assertEqual(list(g1), [])
self.assertEqual(list(g2), [])
self.assertEqual(next(g3), ('A', 5))
self.assertRaises(RuntimeError, next, g1)
self.assertRaises(RuntimeError, next, g2)
self.assertEqual(list(g3), s[5:])
list(it) # exhaust the groupby iterator
self.assertEqual(list(g3), [])
self.assertRaises(RuntimeError, next, g3)

for proto in range(pickle.HIGHEST_PROTOCOL + 1):
it = groupby(s, testR)
_, g = next(it)
next(it)
next(it)
self.assertEqual(list(pickle.loads(pickle.dumps(g, proto))), [])
self.assertRaises(RuntimeError, pickle.dumps, g, proto)

# Exercise pipes and filters style
s = 'abracadabra'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
An iterator produced by itertools.groupby() iterator now becames exhausted
An iterator produced by itertools.groupby() iterator now becames invalid
after advancing the groupby iterator.
7 changes: 5 additions & 2 deletions Modules/itertoolsmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,10 @@ _grouper_next(_grouperobject *igo)
PyObject *newvalue, *newkey, *r;
int rcmp;

if (gbo->currgrouper != igo)
if (gbo->currgrouper != igo) {
PyErr_SetString(PyExc_RuntimeError, "group changed during iteration");
return NULL;
}
if (gbo->currvalue == NULL) {
newvalue = PyIter_Next(gbo->it);
if (newvalue == NULL)
Expand Down Expand Up @@ -327,7 +329,8 @@ static PyObject *
_grouper_reduce(_grouperobject *lz)
{
if (((groupbyobject *)lz->parent)->currgrouper != lz) {
return Py_BuildValue("N(())", _PyObject_GetBuiltin("iter"));
PyErr_SetString(PyExc_RuntimeError, "group changed during iteration");
return NULL;
}
return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->parent, lz->tgtkey);
}
Expand Down