Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed potential issues with removing not completely initialized module from
``sys.modules`` when import fails.
25 changes: 16 additions & 9 deletions Python/import.c
Original file line number Diff line number Diff line change
Expand Up @@ -845,22 +845,29 @@ PyImport_AddModule(const char *name)
}


/* Remove name from sys.modules, if it's there. */
/* Remove name from sys.modules, if it's there.
* Can be called with an exception raised.
* If fail to remove name a new exception will be chained with the old
* exception, otherwise the old exception is preserved.
*/
static void
remove_module(PyObject *name)
{
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
PyObject *modules = PyImport_GetModuleDict();
if (!PyMapping_HasKey(modules, name)) {
goto out;

PyObject *modules = tstate->interp->modules;
if (PyDict_CheckExact(modules)) {
PyObject *mod = _PyDict_Pop(modules, name, Py_None);
Py_XDECREF(mod);
}
if (PyMapping_DelItem(modules, name) < 0) {
Py_FatalError("import: deleting existing key in "
"sys.modules failed");
else if (PyMapping_DelItem(modules, name) < 0) {
if (PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear();
}
}
out:
PyErr_Restore(type, value, traceback);

_PyErr_ChainExceptions(type, value, traceback);
}


Expand Down