python / python/cpython

`"import"` audit hook documentation is misleading

未关闭
#116,840 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

docs
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Documentation

The documentation for the import statement states that it:

Raises an auditing event import with arguments module, filename, sys.path, sys.meta_path, sys.path_hooks.

However, this is not the case if the target of the import is already in sys.modules, as the audit event is raised only on first import. For imports of Python source, the event fires from import_find_and_load(), which is called from PyImport_ImportModuleLevelObject() only if the module is not already loaded.

The docs seem to suggest that the audit event is associated with the statement, but the docs are wrong.

Promote to bug?

I'm filing this as a documentation issue because the docs are not describing this behavior, but it seems that it may represent a bug in CPython. I'm willing to write a patch either way and would like a core developer to decide if this is a docs problem or a runtime problem.

It seems to me that there are a lot of use cases where a user really does want an audit event for every import statement, regardless of whether or not the module has already been imported. In fact, I found this quirk specifically because of one of these use cases. I had an application running import torch in a place where that (memory-hungry) import needed to be deferred, but the output of my debugging audit hook showed me only the first import (which luckily was still enough information to fix the problem).

If a core developer agrees that it makes sense to raise this event even if the target module is already present in sys.modules, this could be promoted to a CPython bug.

Sample program

# target_program.py
import sys
import hook
sys.addaudithook(hook.audit_numpy_import)

# BEGIN unmodified target program
import numpy

from helper import somefunc  # also runs `import numpy`


def random_array():
    arr = np.random.randint(0, 255, size=(30, 50))

    return arr, somefunc()
helper.py
import numpy


def somefunc():
    return numpy.array([42])
hook.py
import inspect
import sys


def audit_numpy_import(event, args):
    if event != "import":
        return

    TARGET_MODULE = "numpy"

    module, filename, syspath, sysmeta_path, syspath_hooks = args
    if module == TARGET_MODULE:
        stack = inspect.stack()
        target_frame = stack[1]  # index 0 is *this* frame, index 1 is where the audit event happened
        fn = target_frame.filename
        lineno = target_frame.lineno
        print(f"{TARGET_MODULE} imported at {fn}:{lineno}")

Running the above instrument program produces the output:

$ python3 target_program.py
numpy imported at /tmp/whats-importing-that-module/target_program.py:8

Where the output I wanted is:

numpy imported at /tmp/whats-importing-that-module/target_program.py:8
numpy imported at /tmp/whats-importing-that-module/helper.py:1

I've confirmed that I can get the above output if I add sys.modules.pop("numpy") after the first numpy import, but unfortunately this (unreliable!) workaround cannot be used from the audit hook, since the module is not placed there until after the hook has finished executing.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Doc/reference/simple_stmts.rst 中关于 import 语句的文档开始,将其中关于审计事件的措辞与 Python/import.c 中描述的行为进行比较,尤其关注 import_find_and_load() 和 PyImport_ImportModuleLevelObject()。运行示例程序以重现这一差异。当项目确定这是文档问题还是运行时问题,并且相关行为得到准确覆盖时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
documentation
Issue 类型
文档
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。