python / python/cpython

LazyImportType.resolve() does not replace the module global and can import twice

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

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

interpreter-core topic-lazy-imports type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

Calling resolve() on a lazy import proxy forces the import and returns the resolved object, but it does not replace the original lazy object in the module globals. A later normal global access reifies the same lazy object again.

import builtins
import types

real_import = builtins.__import__
calls = []

lazy import target_module as target

def custom_import(name, globals=None, locals=None, fromlist=None, level=0):
    if name == "target_module":
        index = len(calls) + 1
        calls.append((index, name, globals.get("__name__"), fromlist))
        module = types.ModuleType(name)
        module.VALUE = f"value-{index}"
        return module
    return real_import(name, globals, locals, fromlist, level)

builtins.__import__ = custom_import
try:
    def resolve_from_dict():
        lazy_obj = globals()["target"]
        resolved = lazy_obj.resolve()
        print("resolved:", resolved.VALUE)
        print("global after resolve:", type(globals()["target"]).__name__)

    resolve_from_dict()

    print("direct:", target.VALUE)
    print("global after direct:", type(globals()["target"]).__name__)
    print("calls:", calls)
finally:
    builtins.__import__ = real_import

Expected: one import, with the module global replaced after resolve().

Actual on current main:

resolved: value-1
global after resolve: lazy_import
direct: value-2
global after direct: module
calls: [(1, 'target_module', '__main__', None), (2, 'target_module', '__main__', None)]

I confirmed this across tier1, tier2, and tier2 without uop optimization:
https://github.com/Kuhai9801/cpython/actions/runs/28243825007

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-152308
  • gh-152524
  • gh-157730

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

issue の reproducer から始め、LazyImportType.resolve() を追跡し、lazy オブジェクトがモジュールのグローバル変数にどのように保存されるかに注目してください。resolve() によって 1 回の import が発生し、モジュールのグローバル変数が置き換えられ、その後の直接アクセスで同じモジュールが返されれば完了です。示されている呼び出しと出力に対して検証してください。

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

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
30/100

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

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