python / python/cpython

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

未關閉
#152,298 2 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

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. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從 issue 中的 reproducer 開始,追蹤 LazyImportType.resolve(),重點關注 lazy 物件如何儲存在模組全域變數中。當 resolve() 導致一次 import、取代模組全域變數,且之後的直接存取回傳相同的模組時,即表示完成;根據所示的呼叫和輸出進行驗證。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
缺陷
難度
3/5
預估耗時
1-2 天
活躍度
停滯
描述清晰度
描述清楚
新手友好度
30/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。