diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py index 6eb25960101a9e..dce0eb8ee18291 100644 --- a/Lib/test/test_generators.py +++ b/Lib/test/test_generators.py @@ -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), diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-30-11-44-38.gh-issue-162576.LpD6MA.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-30-11-44-38.gh-issue-162576.LpD6MA.rst new file mode 100644 index 00000000000000..4903b7ca8240f9 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-30-11-44-38.gh-issue-162576.LpD6MA.rst @@ -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. diff --git a/Objects/genobject.c b/Objects/genobject.c index 82a1bb1ff42068..5ad985cd2ef8ba 100644 --- a/Objects/genobject.c +++ b/Objects/genobject.c @@ -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; }