Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Lib/test/test_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,24 @@ def generator(arg):
g.gi_frame.clear()
self.assertTrue(DetectDelete.deleted)

def test_return_value_stopiteration_context(self):
# gh-162576: StopIteration raised when a generator returns a non-None
# value must have __context__ set when raised inside an except block.
def gen(v):
return v
yield

for v in (5, 'x', [], (1, 2), False, 0, b'bytes'):
with self.subTest(v=v):
try:
try:
raise KeyError('handled')
except KeyError:
next(gen(v))
except StopIteration as e:
self.assertIsInstance(e.__context__, KeyError)
self.assertEqual(e.value, v)

class ModifyUnderlyingIterableTest(unittest.TestCase):
iterables = [
range(0),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix :exc:`StopIteration` raised by a generator that returns a non-``None``
value losing its ``__context__`` when raised inside an active exception
handler. The ``__context__`` was erroneously ``None`` instead of the
currently handled exception.
14 changes: 8 additions & 6 deletions Objects/genobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -785,18 +785,20 @@ int
_PyGen_SetStopIterationValue(PyObject *value)
{
assert(!PyErr_Occurred());
// Construct an exception instance manually with PyObject_CallOneArg()
// but use PyErr_SetRaisedException() instead of PyErr_SetObject() as
// PyErr_SetObject(exc_type, value) has a fast path when 'value'
// is a tuple, where the value of the StopIteration exception would be
// set to 'value[0]' instead of 'value'.
// Construct the instance first to avoid PyErr_SetObject()'s tuple
// fast-path: PyErr_SetObject(StopIteration, (a, b)) would set
// args=(a,) instead of args=((a, b),). Passing the already-constructed
// instance back through PyErr_SetObject() gets us implicit __context__
// chaining for free; the tuple fast-path is bypassed because the value
// is already a StopIteration instance, not a raw tuple.
PyObject *exc = value == NULL
? PyObject_CallNoArgs(PyExc_StopIteration)
: PyObject_CallOneArg(PyExc_StopIteration, value);
if (exc == NULL) {
return -1;
}
PyErr_SetRaisedException(exc /* stolen */);
PyErr_SetObject(PyExc_StopIteration, exc);
Py_DECREF(exc);
return 0;
}

Expand Down
Loading