diff -r b255ecb175c4 Python/import.c --- a/Python/import.c Mon Jul 07 23:07:27 2014 +0200 +++ b/Python/import.c Mon Jul 07 23:09:22 2014 +0200 @@ -345,10 +345,49 @@ PyImport_Cleanup(void) PyObject *modules = interp->modules; PyObject *weaklist = NULL; char **p; + _Py_IDENTIFIER(__main__); if (modules == NULL) return; /* Already done */ + /* We prepare a list which will receive (name, weakref) tuples of + modules when they are removed from sys.modules. The name is used + for diagnosis messages (in verbose mode), while the weakref helps + detect those modules which have been held alive. */ + weaklist = PyList_New(0); + if (weaklist == NULL) + PyErr_Clear(); + +#define STORE_MODULE_WEAKREF(name, mod) \ + if (weaklist != NULL) { \ + PyObject *wr = PyWeakref_NewRef(mod, NULL); \ + if (name && wr) { \ + PyObject *tup = PyTuple_Pack(2, name, wr); \ + PyList_Append(weaklist, tup); \ + Py_XDECREF(tup); \ + } \ + Py_XDECREF(wr); \ + if (PyErr_Occurred()) \ + PyErr_Clear(); \ + } + + /* Remove __main__ module */ + key = _PyUnicode_FromId(&PyId___main__); + if (key != NULL) + value = PyDict_GetItemWithError(modules, key); + else + value = NULL; + if (value != NULL) { + if (PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_FormatStderr("# cleanup[2] removing %U\n", key); + STORE_MODULE_WEAKREF(key, value); + PyDict_SetItem(modules, key, Py_None); + } + } + else + PyErr_Clear(); + /* Delete some special variables first. These are common places where user values hide and people complain when their destructors fail. Since the modules containing them are @@ -375,27 +414,6 @@ PyImport_Cleanup(void) PyDict_SetItemString(interp->sysdict, *p, value); } - /* We prepare a list which will receive (name, weakref) tuples of - modules when they are removed from sys.modules. The name is used - for diagnosis messages (in verbose mode), while the weakref helps - detect those modules which have been held alive. */ - weaklist = PyList_New(0); - if (weaklist == NULL) - PyErr_Clear(); - -#define STORE_MODULE_WEAKREF(name, mod) \ - if (weaklist != NULL) { \ - PyObject *wr = PyWeakref_NewRef(mod, NULL); \ - if (name && wr) { \ - PyObject *tup = PyTuple_Pack(2, name, wr); \ - PyList_Append(weaklist, tup); \ - Py_XDECREF(tup); \ - } \ - Py_XDECREF(wr); \ - if (PyErr_Occurred()) \ - PyErr_Clear(); \ - } - /* Remove all modules from sys.modules, hoping that garbage collection can reclaim most of them. */ pos = 0;