From bfff02c00385feba46a425a25ade7200649736e0 Mon Sep 17 00:00:00 2001 From: Christopher Schramm Date: Fri, 10 Feb 2023 18:15:50 +0400 Subject: [PATCH 1/2] gh-71587: Clear cached strptime module --- Modules/_datetimemodule.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Modules/_datetimemodule.c b/Modules/_datetimemodule.c index eda8c5610ba659..27b8d1897538dc 100644 --- a/Modules/_datetimemodule.c +++ b/Modules/_datetimemodule.c @@ -5189,22 +5189,23 @@ datetime_utcfromtimestamp(PyObject *cls, PyObject *args) return result; } +static PyObject *strptime_module = NULL; + /* Return new datetime from _strptime.strptime_datetime(). */ static PyObject * datetime_strptime(PyObject *cls, PyObject *args) { - static PyObject *module = NULL; PyObject *string, *format; if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format)) return NULL; - if (module == NULL) { - module = PyImport_ImportModule("_strptime"); - if (module == NULL) + if (strptime_module == NULL) { + strptime_module = PyImport_ImportModule("_strptime"); + if (strptime_module == NULL) return NULL; } - return PyObject_CallMethodObjArgs(module, &_Py_ID(_strptime_datetime), + return PyObject_CallMethodObjArgs(strptime_module, &_Py_ID(_strptime_datetime), cls, string, format, NULL); } @@ -6863,12 +6864,17 @@ _datetime_exec(PyObject *module) return 0; } +static void module_free(void*) { + strptime_module = NULL; +} + static struct PyModuleDef datetimemodule = { PyModuleDef_HEAD_INIT, .m_name = "_datetime", .m_doc = "Fast implementation of the datetime type.", .m_size = -1, .m_methods = module_methods, + .m_free = module_free, }; PyMODINIT_FUNC From fe1c392b14b1ce3cc5af95f3f92c5b7515e5f2af Mon Sep 17 00:00:00 2001 From: Alexander Belopolsky Date: Sat, 11 Feb 2023 07:53:15 +0400 Subject: [PATCH 2/2] gh-71587: Don't leak a reference --- Modules/_datetimemodule.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/_datetimemodule.c b/Modules/_datetimemodule.c index 27b8d1897538dc..2d96b7acce54c0 100644 --- a/Modules/_datetimemodule.c +++ b/Modules/_datetimemodule.c @@ -6864,8 +6864,8 @@ _datetime_exec(PyObject *module) return 0; } -static void module_free(void*) { - strptime_module = NULL; +static void module_free(void *_) { + Py_CLEAR(strptime_module); } static struct PyModuleDef datetimemodule = {