Skip to content

Commit 5573d36

Browse files
pythongh-101892: Fix SystemError when a callable iterator call exhausts the iterator (python#101896)
Co-authored-by: Oleg Iarygin <oleg@arhadthedev.net> (cherry picked from commit 705487c)
1 parent d104234 commit 5573d36

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

Lib/test/test_iter.py

+25
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,31 @@ def spam(state=[0]):
266266
return i
267267
self.check_iterator(iter(spam, 20), list(range(10)), pickle=False)
268268

269+
def test_iter_function_concealing_reentrant_exhaustion(self):
270+
# gh-101892: Test two-argument iter() with a function that
271+
# exhausts its associated iterator but forgets to either return
272+
# a sentinel value or raise StopIteration.
273+
HAS_MORE = 1
274+
NO_MORE = 2
275+
276+
def exhaust(iterator):
277+
"""Exhaust an iterator without raising StopIteration."""
278+
list(iterator)
279+
280+
def spam():
281+
# Touching the iterator with exhaust() below will call
282+
# spam() once again so protect against recursion.
283+
if spam.is_recursive_call:
284+
return NO_MORE
285+
spam.is_recursive_call = True
286+
exhaust(spam.iterator)
287+
return HAS_MORE
288+
289+
spam.is_recursive_call = False
290+
spam.iterator = iter(spam, NO_MORE)
291+
with self.assertRaises(StopIteration):
292+
next(spam.iterator)
293+
269294
# Test exception propagation through function iterator
270295
def test_exception_function(self):
271296
def spam(state=[0]):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Callable iterators no longer raise :class:`SystemError` when the
2+
callable object exhausts the iterator but forgets to either return a
3+
sentinel value or raise :class:`StopIteration`.

Objects/iterobject.c

+2-2
Original file line numberDiff line numberDiff line change
@@ -218,15 +218,14 @@ calliter_iternext(calliterobject *it)
218218
}
219219

220220
result = _PyObject_CallNoArg(it->it_callable);
221-
if (result != NULL) {
221+
if (result != NULL && it->it_sentinel != NULL){
222222
int ok;
223223

224224
ok = PyObject_RichCompareBool(it->it_sentinel, result, Py_EQ);
225225
if (ok == 0) {
226226
return result; /* Common case, fast path */
227227
}
228228

229-
Py_DECREF(result);
230229
if (ok > 0) {
231230
Py_CLEAR(it->it_callable);
232231
Py_CLEAR(it->it_sentinel);
@@ -237,6 +236,7 @@ calliter_iternext(calliterobject *it)
237236
Py_CLEAR(it->it_callable);
238237
Py_CLEAR(it->it_sentinel);
239238
}
239+
Py_XDECREF(result);
240240
return NULL;
241241
}
242242

0 commit comments

Comments
 (0)