Skip to content

Commit 45c02dc

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 45c02dc

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

Python/import.c

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -297,22 +297,28 @@ 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+
}
310311
Py_DECREF(mod);
311312
return NULL;
312313
}
313314
Py_DECREF(mod_check);
314315
}
315316
return mod;
317+
318+
error:
319+
Py_DECREF(mod);
320+
remove_importlib_frames(tstate);
321+
return NULL;
316322
}
317323

318324
/* Get the module object corresponding to a module name.
@@ -3901,6 +3907,10 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
39013907
PyObject *mod_check = import_get_module(tstate, abs_name);
39023908
if (mod_check != mod) {
39033909
Py_XDECREF(mod_check);
3910+
if (_PyErr_Occurred(tstate)) {
3911+
Py_DECREF(mod);
3912+
goto error;
3913+
}
39043914
Py_DECREF(mod);
39053915
mod = import_find_and_load(tstate, abs_name);
39063916
if (mod == NULL) {

0 commit comments

Comments
 (0)