10000 GH-98363: Fix exception handling in batched() by rhettinger · Pull Request #98523 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

GH-98363: Fix exception handling in batched() #98523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 21, 2022
Merged
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
15 changes: 15 additions & 0 deletions Lib/test/test_itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2012,6 +2012,20 @@ def __iter__(self):
def __next__(self):
3 // 0

class E2:
'Test propagation of exceptions after two iterations'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i == 2:
raise ZeroDivisionError
v = self.seqn[self.i]
self.i += 1
return v

class S:
'Test immediate stop'
def __init__(self, seqn):
Expand Down Expand Up @@ -2050,6 +2064,7 @@ def test_batched(self):
self.assertRaises(TypeError, batched, X(s), 2)
self.assertRaises(TypeError, batched, N(s), 2)
self.assertRaises(ZeroDivisionError, list, batched(E(s), 2))
self.assertRaises(ZeroDivisionError, list, batched(E2(s), 4))

def test_chain(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Expand Down
29 changes: 21 additions & 8 deletions Modules/itertoolsmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -154,23 +154,36 @@ batched_next(batchedobject *bo)
if (result == NULL) {
return NULL;
}
iternextfunc iternext = *Py_TYPE(it)->tp_iternext;
PyObject **items = PySequence_Fast_ITEMS(result);
for (i=0 ; i < n ; i++) {
item = PyIter_Next(it);
item = iternext(it);
if (item == NULL) {
break;
goto null_item;
}
items[i] = item;
}
return result;

null_item:
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
PyErr_Clear();
} else {
/* input raised an exception other than StopIteration */
Py_CLEAR(bo->it);
Py_DECREF(result);
return NULL;
}
PyList_SET_ITEM(result, i, item);
}
if (i == 0) {
Py_CLEAR(bo->it);
Py_DECREF(result);
return NULL;
}
if (i < n) {
PyObject *short_list = PyList_GetSlice(result, 0, i);
Py_SETREF(result, short_list);
}
return result;
PyObject *short_list = PyList_GetSlice(result, 0, i);
Py_DECREF(result);
return short_list;
}

static PyTypeObject batched_type = {
Expand Down
0