diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py index cd8b4a4f3b1..57519015840 100644 --- a/Lib/test/test_import.py +++ b/Lib/test/test_import.py @@ -8,7 +8,8 @@ import sys import unittest from test.test_support import (unlink, TESTFN, unload, run_unittest, rmtree, is_jython, check_warnings, EnvironmentVarGuard) - +import textwrap +from test import script_helper def remove_files(name): for f in (name + os.extsep + "py", @@ -253,6 +254,17 @@ class ImportTests(unittest.TestCase): 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 diff --git a/Misc/NEWS b/Misc/NEWS index faef735e203..780d6b1da4c 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -9,6 +9,10 @@ What's New in Python 2.7.2? Core and Builtins ----------------- +- Issue #4236: Py_InitModule4 now checks the import machinery directly + rather than the Py_IsInitialized flag, avoiding a Fatal Python + error in certain circumstances when an import is done in __del__. + - Issue #10674: Remove unused 'dictmaker' rule from grammar. - Issue #10596: Fix float.__mod__ to have the same behaviour as diff --git a/Python/modsupport.c b/Python/modsupport.c index 6ee48f3f1e4..8bdec8b7924 100644 --- a/Python/modsupport.c +++ b/Python/modsupport.c @@ -34,8 +34,9 @@ Py_InitModule4(const char *name, PyMethodDef *methods, const char *doc, { PyObject *m, *d, *v, *n; PyMethodDef *ml; - 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 (module_api_version != PYTHON_API_VERSION) { char message[512]; PyOS_snprintf(message, sizeof(message),