Skip to content

Commit 705487c

Browse files
gh-101892: Fix SystemError when a callable iterator call exhausts the iterator (#101896)
Co-authored-by: Oleg Iarygin <[email protected]>
1 parent b022250 commit 705487c

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

Lib/test/test_iter.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,31 @@ def spam(state=[0]):
348348
return i
349349
self.check_iterator(iter(spam, 20), list(range(10)), pickle=False)
350350

351+
def test_iter_function_concealing_reentrant_exhaustion(self):
352+
# gh-101892: Test two-argument iter() with a function that
353+
# exhausts its associated iterator but forgets to either return
354+
# a sentinel value or raise StopIteration.
355+
HAS_MORE = 1
356+
NO_MORE = 2
357+
358+
def exhaust(iterator):
359+
"""Exhaust an iterator without raising StopIteration."""
360+
list(iterator)
361+
362+
def spam():
363+
# Touching the iterator with exhaust() below will call
364+
# spam() once again so protect against recursion.
365+
if spam.is_recursive_call:
366+
return NO_MORE
367+
spam.is_recursive_call = True
368+
exhaust(spam.iterator)
369+
return HAS_MORE
370+
371+
spam.is_recursive_call = False
372+
spam.iterator = iter(spam, NO_MORE)
373+
with self.assertRaises(StopIteration):
374+
next(spam.iterator)
375+
351376
# Test exception propagation through function iterator
352377
def test_exception_function(self):
353378
def spam(state=[0]):
Lines changed: 3 additions & 0 deletions
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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,15 +219,14 @@ calliter_iternext(calliterobject *it)
219219
}
220220

221221
result = _PyObject_CallNoArgs(it->it_callable);
222-
if (result != NULL) {
222+
if (result != NULL && it->it_sentinel != NULL){
223223
int ok;
224224

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

230-
Py_DECREF(result);
231230
if (ok > 0) {
232231
Py_CLEAR(it->it_callable);
233232
Py_CLEAR(it->it_sentinel);
@@ -238,6 +237,7 @@ calliter_iternext(calliterobject *it)
238237
Py_CLEAR(it->it_callable);
239238
Py_CLEAR(it->it_sentinel);
240239
}
240+
Py_XDECREF(result);
241241
return NULL;
242242
}
243243

0 commit comments

Comments
 (0)