diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-04-25-09-05-47.gh-issue-132713.rHfLvU.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-25-09-05-47.gh-issue-132713.rHfLvU.rst new file mode 100644 index 00000000000000..3a1aff743a075a --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-25-09-05-47.gh-issue-132713.rHfLvU.rst @@ -0,0 +1,2 @@ +Fix ``repr(classmethod)`` race condition: hold a strong reference to the +callable while calling ``repr(classmethod)``. Patch by Victor Stinner. diff --git a/Objects/funcobject.c b/Objects/funcobject.c index 6d71dbb5a6affd..ad7e6849137480 100644 --- a/Objects/funcobject.c +++ b/Objects/funcobject.c @@ -1488,7 +1488,12 @@ static PyObject* cm_repr(PyObject *self) { classmethod *cm = _PyClassMethod_CAST(self); - return PyUnicode_FromFormat("", cm->cm_callable); + // gh-132713: Hold a strong reference since cm_init() can be called + // in parallel + PyObject *callable = Py_NewRef(cm->cm_callable); + PyObject *repr = PyUnicode_FromFormat("", callable); + Py_DECREF(callable); + return repr; } PyDoc_STRVAR(classmethod_doc,