`lazy import a.b as c` incorrectly binds to `a.b.b`
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- 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