Skip to content

Commit 441de32

Browse files
Lisa CarrierLisa Carrier
authored andcommitted
Moves audit to _gcd_import.
1 parent 391e1de commit 441de32

3 files changed

Lines changed: 10 additions & 12 deletions

File tree

Lib/importlib/__init__.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -86,16 +86,6 @@ def import_module(name, package=None):
8686
break
8787
level += 1
8888
module = _bootstrap._gcd_import(name[level:], package, level)
89-
if module:
90-
sys.audit(
91-
"import",
92-
name,
93-
# We could try to grab __file__ here but it breaks LazyLoader
94-
None,
95-
sys.path,
96-
sys.meta_path,
97-
sys.path_hooks
98-
)
9989
return module
10090

10191

Lib/importlib/_bootstrap.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1395,6 +1395,10 @@ def _gcd_import(name, package=None, level=0):
13951395
_sanity_check(name, package, level)
13961396
if level > 0:
13971397
name = _resolve_name(name, package, level)
1398+
module = sys.modules.get(name, _NEEDS_LOADING)
1399+
if (module is _NEEDS_LOADING or
1400+
getattr(getattr(module, "__spec__", None), "_initializing", False)):
1401+
sys.audit("import", name, None, sys.path, sys.meta_path, sys.path_hooks)
13981402
return _find_and_load(name, _gcd_import)
13991403

14001404

Lib/test/audit-tests.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -676,14 +676,18 @@ def test_import_module():
676676
import importlib
677677

678678
with TestHook() as hook:
679-
importlib.import_module("os") # random stdlib
679+
importlib.import_module("importlib") # already imported, won't get logged
680+
importlib.import_module("email") # standard library module
680681
importlib.import_module("pythoninfo") # random module
682+
importlib.import_module(".test_importlib.abc", "test") # relative import
681683

682684
actual = [a[0] for e, a in hook.seen if e == "import"]
683685
assertSequenceEqual(
684686
[
685-
"os",
687+
"email",
686688
"pythoninfo",
689+
"test.test_importlib.abc",
690+
"test.test_importlib"
687691
],
688692
actual,
689693
)

0 commit comments

Comments
 (0)