Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Lib/importlib/_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Loading