bpo-36370: Check for PyErr_Occurred() after PyImport_GetModule() (GH-12504)
diff --git a/Python/import.c b/Python/import.c
index ccdd599..63c99ea 100644
--- a/Python/import.c
+++ b/Python/import.c
@@ -953,11 +953,10 @@
Py_DECREF(v);
m = PyImport_GetModule(name);
- if (m == NULL) {
+ if (m == NULL && !PyErr_Occurred()) {
PyErr_Format(PyExc_ImportError,
"Loaded module %R not found in sys.modules",
name);
- return NULL;
}
return m;
@@ -1714,6 +1713,10 @@
}
mod = PyImport_GetModule(abs_name);
+ if (mod == NULL && PyErr_Occurred()) {
+ goto error;
+ }
+
if (mod != NULL && mod != Py_None) {
_Py_IDENTIFIER(__spec__);
_Py_IDENTIFIER(_initializing);
@@ -1801,9 +1804,11 @@
final_mod = PyImport_GetModule(to_return);
Py_DECREF(to_return);
if (final_mod == NULL) {
- PyErr_Format(PyExc_KeyError,
- "%R not in sys.modules as expected",
- to_return);
+ if (!PyErr_Occurred()) {
+ PyErr_Format(PyExc_KeyError,
+ "%R not in sys.modules as expected",
+ to_return);
+ }
goto error;
}
}
@@ -1855,6 +1860,10 @@
PyObject *reloaded_module = NULL;
PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
if (imp == NULL) {
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+
imp = PyImport_ImportModule("imp");
if (imp == NULL) {
return NULL;