diff --git a/numpy/_core/src/multiarray/multiarraymodule.c b/numpy/_core/src/multiarray/multiarraymodule.c index 2f381a1c7aa6..8afad4ed93cd 100644 --- a/numpy/_core/src/multiarray/multiarraymodule.c +++ b/numpy/_core/src/multiarray/multiarraymodule.c @@ -5170,7 +5170,13 @@ _multiarray_umath_exec(PyObject *m) { if (PyDataMem_DefaultHandler == NULL) { return -1; } - +#ifdef Py_GIL_DISABLED + if (PyUnstable_SetImmortal(PyDataMem_DefaultHandler) == 0) { + PyErr_SetString(PyExc_RuntimeError, + "Could not mark memory handler capsule as immortal"); + return -1; + } +#endif /* * Initialize the context-local current handler * with the default PyDataMem_Handler capsule. diff --git a/numpy/_core/src/umath/extobj.c b/numpy/_core/src/umath/extobj.c index 91b0b4c62d30..77a76873d20f 100644 --- a/numpy/_core/src/umath/extobj.c +++ b/numpy/_core/src/umath/extobj.c @@ -15,6 +15,7 @@ #include "numpy/ufuncobject.h" #include "common.h" +#include "npy_pycompat.h" #define UFUNC_ERR_IGNORE 0 @@ -145,6 +146,13 @@ init_extobj(void) if (npy_static_pydata.default_extobj_capsule == NULL) { return -1; } +#ifdef Py_GIL_DISABLED + if (PyUnstable_SetImmortal(npy_static_pydata.default_extobj_capsule) == 0) { + PyErr_SetString(PyExc_RuntimeError, "Could not mark extobj capsule as immortal"); + Py_CLEAR(npy_static_pydata.default_extobj_capsule); + return -1; + } +#endif npy_static_pydata.npy_extobj_contextvar = PyContextVar_New( "numpy.ufunc.extobj", npy_static_pydata.default_extobj_capsule); if (npy_static_pydata.npy_extobj_contextvar == NULL) {