Skip to content

importlib.import_module does not fire sys.audit "import" event #138310

@lisroach

Description

@lisroach

Bug report

Bug description:

sys.audit raises auditing events for imports (https://docs.python.org/3/library/audit_events.html) but importlib.import_module does not fire an auditing event.

Repro:

>>> import sys
>>> def print_audit(event, args):
...     if event == "import":
...         print("event found: ", args)
...
>>> import importlib
>>> sys.addaudithook(print_audit)
>>> importlib.import_module("foo")
hello world
<module 'foo' from '/Users/lisacarrier/cpython-dev/test_importlib/foo.py'>
>>> importlib.import_module("os")
<module 'os' (frozen)>

(no "event found" logs)

But if you import using the import statement it does fire an event as expected:

>>> import foo
event found:  ('foo', None, ['', '/Library/Frameworks/Python.framework/Versions/3.14/lib/python314.zip', '/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14', '/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/site-packages'], [<class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>], [<class 'zipimport.zipimporter'>, <function FileFinder.path_hook.<locals>.path_hook_for_FileFinder at 0x104ac0300>])
hello world

In my opinion both should fire audit events, so that way we can capture all import events. I am trying to use sys.audit today to get a view of all imports in my system, and came across this corner case.

CPython versions tested on:

3.15, 3.14, 3.12

Operating systems tested on:

macOS, Linux

Linked PRs

Metadata

Metadata

Assignees

Labels

stdlibStandard Library Python modules in the Lib/ directorytopic-importlibtype-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions