diff --git a/Lib/importlib/__init__.py b/Lib/importlib/__init__.py index e62bdb1654e..dad0833fce0 100644 --- a/Lib/importlib/__init__.py +++ b/Lib/importlib/__init__.py @@ -7,7 +7,7 @@ import sys try: _bootstrap = sys.modules['_frozen_importlib'] -except ImportError: +except KeyError: from . import _bootstrap _bootstrap._setup(sys, imp) else: diff --git a/Lib/importlib/test/test_api.py b/Lib/importlib/test/test_api.py index b7d6cb4effe..8431eab6f7d 100644 --- a/Lib/importlib/test/test_api.py +++ b/Lib/importlib/test/test_api.py @@ -160,9 +160,30 @@ class InvalidateCacheTests(unittest.TestCase): importlib.invalidate_caches() # Shouldn't trigger an exception. +class FrozenImportlibTests(unittest.TestCase): + + def test_no_frozen_importlib(self): + # Should be able to import w/o _frozen_importlib being defined. + modules = {} + for name in ('importlib', 'importlib.__init__', 'importlib._bootstrap', + '_frozen_importlib'): + try: + modules[name] = sys.modules[name] + del sys.modules[name] + except KeyError: + continue + modules['_frozen_importlib'] = None + import importlib + for name, module in modules.items(): + sys.modules[name] = module + + def test_main(): from test.support import run_unittest - run_unittest(ImportModuleTests, FindLoaderTests, InvalidateCacheTests) + run_unittest(ImportModuleTests, + FindLoaderTests, + InvalidateCacheTests, + FrozenImportlibTests) if __name__ == '__main__': diff --git a/Misc/NEWS b/Misc/NEWS index b318e503fd4..8c4aad2b6ba 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -17,6 +17,9 @@ Core and Builtins Library ------- +- Issue #15210: Catch KeyError when imprortlib.__init__ can't find + _frozen_importlib in sys.modules, not ImportError. + - Issue #15030: importlib.abc.PyPycLoader now supports the new source size header field in .pyc files.