Skip to content

Commit 8e69cf3

Browse files
committed
gh-162576: fix StopIteration.__context__ lost when generator returns non-None
1 parent 352cc06 commit 8e69cf3

3 files changed

Lines changed: 30 additions & 6 deletions

File tree

‎Lib/test/test_generators.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,24 @@ def generator(arg):
330330
g.gi_frame.clear()
331331
self.assertTrue(DetectDelete.deleted)
332332

333+
def test_return_value_stopiteration_context(self):
334+
# gh-162576: StopIteration raised when a generator returns a non-None
335+
# value must have __context__ set when raised inside an except block.
336+
def gen(v):
337+
return v
338+
yield
339+
340+
for v in (5, 'x', [], (1, 2), False, 0, b'bytes'):
341+
with self.subTest(v=v):
342+
try:
343+
try:
344+
raise KeyError('handled')
345+
except KeyError:
346+
next(gen(v))
347+
except StopIteration as e:
348+
self.assertIsInstance(e.__context__, KeyError)
349+
self.assertEqual(e.value, v)
350+
333351
class ModifyUnderlyingIterableTest(unittest.TestCase):
334352
iterables = [
335353
range(0),
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix :exc:`StopIteration` raised by a generator that returns a non-``None``
2+
value losing its ``__context__`` when raised inside an active exception
3+
handler. The ``__context__`` was erroneously ``None`` instead of the
4+
currently handled exception.

‎Objects/genobject.c‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -785,18 +785,20 @@ int
785785
_PyGen_SetStopIterationValue(PyObject *value)
786786
{
787787
assert(!PyErr_Occurred());
788-
// Construct an exception instance manually with PyObject_CallOneArg()
789-
// but use PyErr_SetRaisedException() instead of PyErr_SetObject() as
790-
// PyErr_SetObject(exc_type, value) has a fast path when 'value'
791-
// is a tuple, where the value of the StopIteration exception would be
792-
// set to 'value[0]' instead of 'value'.
788+
// Construct the instance first to avoid PyErr_SetObject()'s tuple
789+
// fast-path: PyErr_SetObject(StopIteration, (a, b)) would set
790+
// args=(a,) instead of args=((a, b),). Passing the already-constructed
791+
// instance back through PyErr_SetObject() gets us implicit __context__
792+
// chaining for free; the tuple fast-path is bypassed because the value
793+
// is already a StopIteration instance, not a raw tuple.
793794
PyObject *exc = value == NULL
794795
? PyObject_CallNoArgs(PyExc_StopIteration)
795796
: PyObject_CallOneArg(PyExc_StopIteration, value);
796797
if (exc == NULL) {
797798
return -1;
798799
}
799-
PyErr_SetRaisedException(exc /* stolen */);
800+
PyErr_SetObject(PyExc_StopIteration, exc);
801+
Py_DECREF(exc);
800802
return 0;
801803
}
802804

0 commit comments

Comments
 (0)