Skip to content
Next Next commit
Make PY_UNWIND available as a local event
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.
  • Loading branch information
P403n1x87 committed Mar 19, 2026
commit 07a26bde9fb2832722c52f965741cb1ed9d54f78
11 changes: 7 additions & 4 deletions Include/cpython/monitoring.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ extern "C" {


/* Local events.
* These require bytecode instrumentation */
* Some of these require bytecode instrumentation */

#define PY_MONITORING_EVENT_PY_START 0
#define PY_MONITORING_EVENT_PY_RESUME 1
Expand All @@ -22,15 +22,18 @@ extern "C" {
#define PY_MONITORING_EVENT_BRANCH_LEFT 8
#define PY_MONITORING_EVENT_BRANCH_RIGHT 9
#define PY_MONITORING_EVENT_STOP_ITERATION 10
#define PY_MONITORING_EVENT_PY_UNWIND 11

// TODO: PY_UNWIND requires no instrumentation so this definition is not
// entirely correct.
#define PY_MONITORING_IS_INSTRUMENTED_EVENT(ev) \
((ev) < _PY_MONITORING_LOCAL_EVENTS)
((ev) <= _PY_MONITORING_LOCAL_EVENTS)


/* Other events, mainly exceptions */

#define PY_MONITORING_EVENT_RAISE 11
#define PY_MONITORING_EVENT_EXCEPTION_HANDLED 12
#define PY_MONITORING_EVENT_PY_UNWIND 13
#define PY_MONITORING_EVENT_RAISE 13
#define PY_MONITORING_EVENT_PY_THROW 14
#define PY_MONITORING_EVENT_RERAISE 15

Expand Down
2 changes: 1 addition & 1 deletion Include/internal/pycore_instruments.h
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ PyAPI_DATA(PyObject) _PyInstrumentation_DISABLE;
/* Total tool ids available */
#define PY_MONITORING_TOOL_IDS 8
/* Count of all local monitoring events */
#define _PY_MONITORING_LOCAL_EVENTS 11
#define _PY_MONITORING_LOCAL_EVENTS 12
/* Count of all "real" monitoring events (not derived from other events) */
#define _PY_MONITORING_UNGROUPED_EVENTS 16
/* Count of all monitoring events */
Expand Down
2 changes: 1 addition & 1 deletion Python/ceval.h
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ monitor_unwind(PyThreadState *tstate,
_PyInterpreterFrame *frame,
_Py_CODEUNIT *instr)
{
if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_PY_UNWIND)) {
if (no_tools_for_local_event(tstate, frame, PY_MONITORING_EVENT_PY_UNWIND)) {
return;
}
do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_PY_UNWIND);
Expand Down