python / python/cpython

`"import"` audit hook documentation is misleading

オープン
#116,840 コメント 4 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Doc/reference/simple_stmts.rst の import 文のドキュメントから始め、監査イベントに関する記述を、特に import_find_and_load() と PyImport_ImportModuleLevelObject() に注目して、Python/import.c に記述されている動作と比較してください。サンプルプログラムを実行して不一致を再現してください。プロジェクトがこれをドキュメントの問題とするかランタイムの問題とするかを決定し、関連する動作が正確にカバーされれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
documentation
issue の種類
ドキュメント
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。