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
38 changes: 31 additions & 7 deletions Lib/test/test_lazy_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 3 additions & 1 deletion Python/import.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
Loading