Skip to content

Commit f502244

Browse files
authored
Create a module at shutdown rather than import
1 parent f99a3d9 commit f502244

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

Modules/_datetimemodule.c

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ get_current_module(PyInterpreterState *interp, int *p_reloading)
158158
}
159159

160160
static PyModuleDef datetimemodule;
161+
static int set_current_module(PyInterpreterState *interp, PyObject *mod);
161162

162163
static datetime_state *
163164
_get_current_state(PyObject **p_mod)
@@ -173,7 +174,28 @@ _get_current_state(PyObject **p_mod)
173174
* so we must re-import the module. */
174175
mod = PyImport_ImportModule("_datetime");
175176
if (mod == NULL) {
176-
return NULL;
177+
PyErr_Clear();
178+
/* Create a module at shutdown */
179+
PyObject *dict = PyInterpreterState_GetDict(interp);
180+
if (dict == NULL) {
181+
return NULL;
182+
}
183+
PyObject *spec;
184+
if (PyDict_GetItemStringRef(dict, "datetime_module_spec", &spec) != 1) {
185+
return NULL;
186+
}
187+
mod = PyModule_FromDefAndSpec(&datetimemodule, spec);
188+
if (mod == NULL) {
189+
Py_DECREF(spec);
190+
return NULL;
191+
}
192+
Py_DECREF(spec);
193+
194+
/* The module will be held by heaptypes. Prefer
195+
/* it not to be cached in the interp-dict. */
196+
if (PyModule_ExecDef(mod, &datetimemodule) < 0) {
197+
return NULL;
198+
}
177199
}
178200
}
179201
datetime_state *st = get_module_state(mod);
@@ -198,6 +220,19 @@ set_current_module(PyInterpreterState *interp, PyObject *mod)
198220
if (ref == NULL) {
199221
return -1;
200222
}
223+
224+
if (!PyDict_ContainsString(dict, "datetime_module_spec")) {
225+
PyObject *spec;
226+
if (PyDict_GetItemRef(PyModule_GetDict(mod), &_Py_ID(__spec__), &spec) != 1) {
227+
return -1;
228+
}
229+
if (PyDict_SetItemString(dict, "datetime_module_spec", spec) < 0) {
230+
Py_DECREF(spec);
231+
return -1;
232+
}
233+
Py_DECREF(spec);
234+
}
235+
201236
int rc = PyDict_SetItem(dict, INTERP_KEY, ref);
202237
Py_DECREF(ref);
203238
return rc;

0 commit comments

Comments
 (0)