diff --git a/Misc/NEWS.d/next/C_API/2026-10-21-19-55-00.gh-issue-159739.ctxt01.rst b/Misc/NEWS.d/next/C_API/2026-10-21-19-55-00.gh-issue-159739.ctxt01.rst new file mode 100644 index 000000000000000..10c268e1043c9ed --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2026-10-21-19-55-00.gh-issue-159739.ctxt01.rst @@ -0,0 +1,2 @@ +Avoid a crash if a context watcher is cleared while other context watchers +are being notified. diff --git a/Python/context.c b/Python/context.c index d48543c9e023a61..87f967063a27b20 100644 --- a/Python/context.c +++ b/Python/context.c @@ -169,8 +169,8 @@ notify_context_watchers(PyThreadState *ts, PyContextEvent event, PyObject *ctx) assert(i < CONTEXT_MAX_WATCHERS); if (bits & 1) { PyContext_WatchCallback cb = interp->context_watchers[i]; - assert(cb != NULL); - if (cb(event, ctx) < 0) { + // A previous callback may have cleared this watcher. + if (cb != NULL && cb(event, ctx) < 0) { PyErr_FormatUnraisable( "Exception ignored in %s watcher callback for %R", context_event_name(event), ctx);