From 995b7eb664a85d2e6823fa64bc0c1af33251a551 Mon Sep 17 00:00:00 2001 From: tonghuaroot Date: Sat, 21 Nov 2026 09:56:01 +0800 Subject: [PATCH] gh-162346: Fix lazy import from an unloaded package Reimport a missing parent package before binding a loaded submodule. This keeps lazy imports consistent with the existing eager import behavior. --- Lib/importlib/_bootstrap.py | 6 +++++- Lib/test/test_import/__init__.py | 11 +++++++++++ .../2026-11-21-09-55-07.gh-issue-162346.x8Qm2L.rst | 2 ++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-09-55-07.gh-issue-162346.x8Qm2L.rst diff --git a/Lib/importlib/_bootstrap.py b/Lib/importlib/_bootstrap.py index 9b2a77e883acf19..b86e6e93b6ee13f 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 2ab61827e696234..1d12ee7aa593aee 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 000000000000000..0bd191bb0ba1b12 --- /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.