diff options
| author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2022-10-21 12:31:52 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-10-21 12:31:52 -0500 |
| commit | a5ff80c8bc96210bace3ffb683b01fbd7f4ab76d (patch) | |
| tree | b1aee731a065f83542a5cdb32b769c966f9b86c4 /Modules | |
| parent | ec1f6f5f139868dc2c1116a7c7c878c38c668d53 (diff) | |
| download | cpython-git-a5ff80c8bc96210bace3ffb683b01fbd7f4ab76d.tar.gz | |
GH-98363: Fix exception handling in batched() (GH-98523)
Diffstat (limited to 'Modules')
| -rw-r--r-- | Modules/itertoolsmodule.c | 29 |
1 files changed, 21 insertions, 8 deletions
diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c index 868e8a8b38..627e698fc6 100644 --- a/Modules/itertoolsmodule.c +++ b/Modules/itertoolsmodule.c @@ -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 = { |
