`lazy import a.b as c` incorrectly binds to `a.b.b`
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
Bug report
(Edited by @johnslavik)
To reproduce:
import importlib.metadata
import importlib.metadata as x
lazy import importlib.metadata as lazy_x
print("type(x): ", type(x).__name__) # reifies to importlib.metadata
print("type(lazy_x):", type(lazy_x).__name__) # reifies to importlib.metadata.metadata
x.distributions() # OK
lazy_x.distributions() # AttributeError: 'function' object has no attribute 'distributions'
x is the importlib.metadata module, as expected. lazy_x is instead reified to importlib.metadata.metadata, the function.
The bug is in cached name resolution.
For lazy import a.b as c, the issue reproduces when:
a.bis already insys.modules.a.bhas an attribute namedb.cis reified.
Possible root cause
The problem may be in _PyEval_LazyImportFrom: [Python/ceval.c:3305-3361](https://github.com/python/cpython/blob/cf312cfa64dcaa1700531ec8bc76d56ddd65fb15/Python/ceval.c#L3305-L3361) (3.15 at cf312cfa64dcaa1700531ec8bc76d56ddd65fb15, v3.15.0rc2-22-gcf312cf).
The sys.modules fast path at lines 3313-3331 runs before the base-module computation at 3333-3360 and looks up name directly in d->lz_from.
In the IMPORT_FROM chain generated for import a.b.c as x, however, d->lz_from does not appear to be the module the attribute should be taken from: on the first step it is the full dotted name, and on later steps it is one component short of the base.
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Linked PRs
- gh-157626
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
先檢查連結的 PR gh-157626,然後查看 Python/ceval.c 中約第 3305–3361 行的 _PyEval_LazyImportFrom,重點關注 sys.modules 快速路徑和快取名稱解析。使用 importlib.metadata 範例重現此行為;當 lazy import a.b as c 將 c 綁定到 a.b 而不是 a.b.b,且相關測試涵蓋此回歸時,即表示完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- compilers
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 描述清楚
- 新手友好度
- 35/100