diff --git a/Lib/importlib/_bootstrap.py b/Lib/importlib/_bootstrap.py index 9b2a77e883acf1..b86e6e93b6ee13 100644 --- a/Lib/importlib/_bootstrap.py +++ b/Lib/importlib/_bootstrap.py @@ -1251,7 +1251,11 @@ def _find_and_load_unlocked(name, import_, *, lazy_submodule=False): parent_spec._uninitialized_submodules.pop() if parent: # Set the module as an attribute on its parent. - parent_module = sys.modules[parent] + try: + parent_module = sys.modules[parent] + except KeyError: + _call_with_frames_removed(import_, parent) + parent_module = sys.modules[parent] try: setattr(parent_module, child, module) except AttributeError: diff --git a/Lib/test/test_import/__init__.py b/Lib/test/test_import/__init__.py index 2ab61827e69623..1d12ee7aa593ae 100644 --- a/Lib/test/test_import/__init__.py +++ b/Lib/test/test_import/__init__.py @@ -1642,6 +1642,17 @@ def test_import_from_unloaded_package(self): import package2.submodule1 package2.submodule1.submodule2 + def test_lazy_import_from_unloaded_package(self): + old_mode = sys.get_lazy_imports() + self.addCleanup(sys.set_lazy_imports, old_mode) + self.addCleanup(sys.lazy_modules.difference_update, { + 'package2', 'package2.submodule1', 'package2.submodule2'}) + sys.set_lazy_imports('all') + with uncache('package2', 'package2.submodule1', 'package2.submodule2'), \ + DirsOnSysPath(os.path.join(os.path.dirname(__file__), 'data')): + import package2.submodule1 + package2.submodule1.submodule2 + def test_rebinding(self): # The same data is also used for testing pkgutil.resolve_name() # in test_pkgutil and mock.patch in test_unittest. diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-09-55-07.gh-issue-162346.x8Qm2L.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-09-55-07.gh-issue-162346.x8Qm2L.rst new file mode 100644 index 00000000000000..0bd191bb0ba1b1 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-09-55-07.gh-issue-162346.x8Qm2L.rst @@ -0,0 +1,2 @@ +Fix lazy imports raising :exc:`KeyError` when a submodule removes its parent +package from :data:`sys.modules` during import. Patch by tonghuaroot.