diff --git a/Lib/test/test_lazy_import/__init__.py b/Lib/test/test_lazy_import/__init__.py index 6dd2f7c825e5dd..69a1da7e750d5d 100644 --- a/Lib/test/test_lazy_import/__init__.py +++ b/Lib/test/test_lazy_import/__init__.py @@ -551,17 +551,41 @@ def test_invalid_descendant_retries(self): assert callable(test.test_lazy_import.data.pkg.b.foo) """) - def test_namespace_import_hooks(self): - self.check(""" + @support.subTests('copied_builtins', (False, True)) + @support.subTests('reverse', (False, True)) + def test_namespace_import_hooks(self, copied_builtins, reverse): + self.check(f""" import builtins - first = {'__builtins__': vars(builtins).copy()} - second = {'__builtins__': vars(builtins).copy()} - exec('lazy import xml.dom', first) - exec('lazy import xml.dom', second) + first = {{'__builtins__': vars(builtins)}} + if {copied_builtins!r}: + first['__builtins__'] = vars(builtins).copy() + second = {{'__builtins__': vars(builtins).copy()}} + for namespace in (first, second)[::{-1 if reverse else 1}]: + exec('lazy import xml.dom', namespace) def denied(*args): - raise AssertionError('used another namespace import hook') + raise RuntimeError('private import hook') second['__builtins__']['__import__'] = denied exec('assert xml.dom.__name__ == "xml.dom"', first) + try: + exec('xml.dom', second) + except RuntimeError as exc: + assert str(exc) == 'private import hook', exc + else: + raise AssertionError('private import hook was not called') + """) + + @support.subTests('statement', ( + 'lazy import xml.dom', + 'lazy from xml import dom', + )) + def test_shared_child_ignores_private_import_hook(self, statement): + self.check(f""" + import builtins, sys, xml + def denied(*args): + raise AssertionError('used a private namespace import hook') + namespace = {{'__builtins__': dict(vars(builtins), __import__=denied)}} + exec({statement!r}, namespace) + assert xml.dom is sys.modules['xml.dom'] """) def test_retry_after_recursive_access(self): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-16-00-00.gh-issue-158597.Uq6zPx.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-16-00-00.gh-issue-158597.Uq6zPx.rst new file mode 100644 index 00000000000000..3e542c13907f4a --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-16-00-00.gh-issue-158597.Uq6zPx.rst @@ -0,0 +1,3 @@ +Prevent a lazy import from using another namespace's ``__import__`` hook +when it resolves a submodule through a shared package attribute. Private +hooks remain attached to their own lazy bindings. diff --git a/Python/import.c b/Python/import.c index 0f01815c71ed36..563454466cf78b 100644 --- a/Python/import.c +++ b/Python/import.c @@ -4547,7 +4547,9 @@ _PyImport_LazyImportModuleLevelObject(PyThreadState *tstate, } } } - else if (register_lazy_on_parent(tstate, abs_name, res) < 0) { + else if (register_lazy_on_parent(tstate, abs_name, + builtins == tstate->interp->builtins + ? res : Py_None) < 0) { goto error; }