Skip to content

Commit 06a3bb8

Browse files
miss-islingtonworkingpayloadarhadthedev
authored
gh-101892: Fix SystemError when a callable iterator call exhausts the iterator (GH-101896)
(cherry picked from commit 705487c) Co-authored-by: Raj <51259329+workingpayload@users.noreply.github.com> Co-authored-by: Oleg Iarygin <oleg@arhadthedev.net>
1 parent 00791f2 commit 06a3bb8

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
@@ -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]):
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
@@ -222,15 +222,14 @@ calliter_iternext(calliterobject *it)
222222
}
223223

224224
result = _PyObject_CallNoArgs(it->it_callable);
225-
if (result != NULL) {
225+
if (result != NULL && it->it_sentinel != NULL){
226226
int ok;
227227

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

233-
Py_DECREF(result);
234233
if (ok > 0) {
235234
Py_CLEAR(it->it_callable);
236235
Py_CLEAR(it->it_sentinel);
@@ -241,6 +240,7 @@ calliter_iternext(calliterobject *it)
241240
Py_CLEAR(it->it_callable);
242241
Py_CLEAR(it->it_sentinel);
243242
}
243+
Py_XDECREF(result);
244244
return NULL;
245245
}
246246

0 commit comments

Comments
 (0)