Skip to content

StopIteration from a generator that returns a value has no __context__ #162576

Backlog

Description

@Robertboy18

Bug report

Bug description:

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:

def g(v):
    return v
    yield
for v in (None, 5):
    try:
        try:
            raise KeyError("handled")
        except KeyError:
            next(g(v))
    except StopIteration as e:
        print(repr(v), repr(e.__context__))
None KeyError('handled')
5 None

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.

CPython versions tested on:

3.15, CPython main branch

Operating systems tested on:

Linux

Activity

  1. added
    interpreter-core
    type-bug
    on Nov 24, 2026
  2. ittec-collab commented on Nov 24, 2026

    @ittec-collab

    I tested the reproducer on Ubuntu Linux with Python 3.14.4 (/usr/bin/python3).

    The issue is reproducible on my system.

    Environment:

    • Python: 3.14.4
    • OS: Ubuntu Linux
    • Architecture: x86_64

    Actual output:

    Return value: None
    Exception context: KeyError('handled')
    ----------------------------------------
    Return value: 5
    Exception context: None
    ----------------------------------------
    

    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.

  3. ittec-collab commented on Nov 24, 2026

    @ittec-collab

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions