Skip to content

Commit 842c160

Browse files
gpsheadclaude
andcommitted
Address review: handle import_get_module errors in race condition fix
Add error checking inside the `if (mod_check != mod)` block to properly handle the case where import_get_module itself fails with an exception. Also refactor PyImport_GetModule to use an error label for cleanup. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 0a682cd commit 842c160

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

Python/import.c

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -297,22 +297,32 @@ PyImport_GetModule(PyObject *name)
297297
mod = import_get_module(tstate, name);
298298
if (mod != NULL && mod != Py_None) {
299299
if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
300-
Py_DECREF(mod);
301-
remove_importlib_frames(tstate);
302-
return NULL;
300+
goto error;
303301
}
304302
/* Verify the module is still in sys.modules. Another thread may have
305303
removed it (due to import failure) between our import_get_module()
306304
call and the _initializing check in import_ensure_initialized(). */
307305
PyObject *mod_check = import_get_module(tstate, name);
308306
if (mod_check != mod) {
309307
Py_XDECREF(mod_check);
308+
if (_PyErr_Occurred(tstate)) {
309+
goto error;
310+
}
311+
/* The module was removed or replaced. Return NULL to report
312+
"not found" rather than trying to keep up with racing
313+
modifications to sys.modules; returning the new value would
314+
require looping to redo the ensure_initialized check. */
310315
Py_DECREF(mod);
311316
return NULL;
312317
}
313318
Py_DECREF(mod_check);
314319
}
315320
return mod;
321+
322+
error:
323+
Py_DECREF(mod);
324+
remove_importlib_frames(tstate);
325+
return NULL;
316326
}
317327

318328
/* Get the module object corresponding to a module name.
@@ -3901,6 +3911,10 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
39013911
PyObject *mod_check = import_get_module(tstate, abs_name);
39023912
if (mod_check != mod) {
39033913
Py_XDECREF(mod_check);
3914+
if (_PyErr_Occurred(tstate)) {
3915+
Py_DECREF(mod);
3916+
goto error;
3917+
}
39043918
Py_DECREF(mod);
39053919
mod = import_find_and_load(tstate, abs_name);
39063920
if (mod == NULL) {

0 commit comments

Comments
 (0)