You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
StopIteration from a generator that returns a value has no __context__ #162576
When a generator returns a value other than None while an exception is being handled, the StopIteration raised by next() has no __context__, and its traceback has no "During handling of the above exception" part. With a bare return it has the context:
The docs say "When raising a new exception while another exception is already being handled, the new exception's __context__ attribute is automatically set to the handled exception" (Exception context). Since gh-128287, _PyGen_SetStopIterationValue (Objects/genobject.c) creates the exception itself and sets it with PyErr_SetRaisedException, which doesn't chain; PyErr_SetObject(PyExc_StopIteration, exc) with the instance would chain and still avoid the tuple fast path. I found it while writing a Lean spec of Python.
The behavior matches the reported issue: when the generator returns a non-None value, the resulting StopIteration loses the context of the currently handled KeyError.
This confirms that the behavior is also present in Python 3.14.4.
I'd like to work on this.
I plan to make the non-None path preserve __context__ while keeping the current behavior for tuple return values, and add a regression test. I'll open a PR.
Activity
ittec-collab commentedon Nov 24, 2026
I tested the reproducer on Ubuntu Linux with Python 3.14.4 (
/usr/bin/python3).The issue is reproducible on my system.
Environment:
Actual output:
The behavior matches the reported issue: when the generator returns a non-None value, the resulting
StopIterationloses the context of the currently handledKeyError.This confirms that the behavior is also present in Python 3.14.4.
ittec-collab commentedon Nov 24, 2026
I'd like to work on this.
I plan to make the non-None path preserve
__context__while keeping the current behavior for tuple return values, and add a regression test. I'll open a PR.