Skip to content

for loop swallows exceptions raised by a sys.monitoring callback for StopIteration #160676

Description

@ashm-dev

Bug report

When a sys.monitoring.events.RAISE callback raises RuntimeError while reporting StopIteration at a for loop, the RuntimeError is swallowed. Execution continues after the loop.

Reproducer

Save as mre_monitoring_stopiteration.py and run python mre_monitoring_stopiteration.py.

import sys


class Empty:
    def __iter__(self):
        return self

    def __next__(self):
        raise StopIteration


def run():
    for _ in Empty():
        pass


def on_raise(code, offset, exc):
    if code is run.__code__ and isinstance(exc, StopIteration):
        print("callback: raising RuntimeError")
        raise RuntimeError("monitor callback failed")


monitoring = sys.monitoring
monitoring.use_tool_id(3, "stopiteration-repro")
try:
    monitoring.register_callback(3, monitoring.events.RAISE, on_raise)
    monitoring.set_events(3, monitoring.events.RAISE)
    run()
finally:
    monitoring.set_events(3, 0)
    monitoring.register_callback(3, monitoring.events.RAISE, None)
    monitoring.free_tool_id(3)

raise AssertionError("RuntimeError from the monitoring callback was swallowed")

Expected behavior

RuntimeError: monitor callback failed propagates out of run(). The script does not reach the final AssertionError.

Actual behavior

The callback prints:

callback: raising RuntimeError

However, run() returns normally, and the script reaches the final assertion:

AssertionError: RuntimeError from the monitoring callback was swallowed

Replacing the loop in run() with next(Empty()) makes the same callback's RuntimeError propagate on the tested main build.

CPython versions tested on:

CPython main branch, 3.16, 3.15, 3.14

Operating systems tested on:

Linux, macOS

Linked PRs

Activity

  1. added 3 commits that reference this issue on Oct 26, 2026
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-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions