[3.12] gh-117178: Recover lazy loading of self-referential modules (GH-117179) by miss-islington · Pull Request #117319 · python/cpython · GitHub
Skip to content
Merged
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
11 changes: 5 additions & 6 deletions Lib/importlib/util.py
18 changes: 18 additions & 0 deletions Lib/test/test_importlib/test_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,24 @@ def access_module():
# Or multiple load attempts
self.assertEqual(loader.load_count, 1)

def test_lazy_self_referential_modules(self):
# Directory modules with submodules that reference the parent can attempt to access
# the parent module during a load. Verify that this common pattern works with lazy loading.
# json is a good example in the stdlib.
json_modules = [name for name in sys.modules if name.startswith('json')]
with test_util.uncache(*json_modules):
# Standard lazy loading, unwrapped
spec = util.find_spec('json')
loader = util.LazyLoader(spec.loader)
spec.loader = loader
module = util.module_from_spec(spec)
sys.modules['json'] = module
loader.exec_module(module)

# Trigger load with attribute lookup, ensure expected behavior
test_load = module.loads('{}')
self.assertEqual(test_load, {})


if __name__ == '__main__':
unittest.main()