Index: Objects/moduleobject.c =================================================================== --- Objects/moduleobject.c (revision 87237) +++ Objects/moduleobject.c (working copy) @@ -63,8 +63,9 @@ PyMethodDef *ml; const char* name; PyModuleObject *m; - if (!Py_IsInitialized()) - Py_FatalError("Interpreter not initialized (version mismatch?)"); + PyInterpreterState *interp = PyThreadState_Get()->interp; + if (interp->modules == NULL) + Py_FatalError("Python import machinery not initialized"); if (PyType_Ready(&moduledef_type) < 0) return NULL; if (module->m_base.m_index == 0) { Index: Lib/test/test_import.py =================================================================== --- Lib/test/test_import.py (revision 87237) +++ Lib/test/test_import.py (working copy) @@ -9,11 +9,13 @@ import stat import sys import unittest +import textwrap from test.support import ( EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython, make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask, unlink, unload) +from test import script_helper def remove_files(name): @@ -284,7 +286,18 @@ self.assertEqual("Import by filename is not supported.", c.exception.args[0]) + def test_import_in_del_does_not_crash(self): + # Issue 4236 + testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\ + import sys + class C: + def __del__(self): + import imp + sys.argv.insert(0, C()) + """)) + script_helper.assert_python_ok(testfn) + class PycRewritingTests(unittest.TestCase): # Test that the `co_filename` attribute on code objects always points # to the right file, even when various things happen (e.g. both the .py