cpython icon indicating copy to clipboard operation
cpython copied to clipboard

gh-142186: make PY_UNWIND available as a local event

Open P403n1x87 opened this issue 1 month ago • 0 comments

We make the PY_UNWIND monitoring event available as a code-local event to allow trapping on function exit events when an exception bubbles up. This complements the PY_RETURN event by allowing to catch any function exit event.

Example

import random, sys

m, e = sys.monitoring, sys.monitoring.events

m.use_tool_id(0, "debugger")

def monitor(event):
    def _(f):
        m.register_callback(0, event, f)
    return _

@monitor(e.PY_START)
def _(*_, **__):
    print("entering", sys._getframe(1))

@monitor(e.PY_UNWIND)
def _(*_, **__):
    print("exiting ", sys._getframe(1), "with exception")

def foo():
    raise RuntimeError()

def bar():
    return foo()

def baz():
    return bar()

m.set_local_events(0, random.choice([foo, bar, baz]).__code__, e.PY_UNWIND | e.PY_START)

try:
    baz()
except Exception:
    pass

# entering <frame at 0x101602f80, file 'test_py_unwind_local.py', line 34, code baz>
# exiting  <frame at 0x101602f80, file 'test_py_unwind_local.py', line 35, code baz> with exception
  • Issue: gh-142186

P403n1x87 avatar Dec 02 '25 10:12 P403n1x87