python / python/cpython

Importing `bz2` will succeed under `lazy_imports=all` even if bz2 is not supported

未关闭
#150,167 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

3.15 3.16 stdlib topic-lazy-imports type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Edit: Originally this bug was expressed through shutil's support detection. shutil now directly imports from _bz2 which works around this issue.

Bug description:

Under lazy_imports=all, modules imported in a try/except block are still imported eagerly. However, imports that occur within that module are still imported lazily.

This may be intentional, but this bug is the result of that behaviour.

On CPython built without bz2 support:

$ PYTHON_LAZY_IMPORTS=normal ./python -c "import shutil; print(shutil._BZ2_SUPPORTED)"
False
$ PYTHON_LAZY_IMPORTS=all ./python -c "import shutil; print(shutil._BZ2_SUPPORTED)"
True

The try/except check is on bz2, which succeeds because the import to _bz2 which would fail is converted to a lazy import and is not used at top level so the import which would fail isn't triggered.

https://github.com/python/cpython/blob/87a879f4d0ec2e545e84c898c5ce452a6c87b09e/Lib/shutil.py#L21-L26

shutil could directly check _bz2 in this particular case, but I expect this pattern isn't uncommon. I looked into this after I ran into a similar issue with pip and rich with an OS-specific import that should have failed in a similar manner.

Related: https://github.com/python/cpython/issues/149640 as this also causes test_shutil to fail under lazy_imports=all if _bz2 isn't present.

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Linked PRs
  • gh-150279
  • gh-154771
  • gh-157321

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Lib/shutil.py 第 21-26 行开始,在不支持 bz2 的 CPython 构建中复现两种 PYTHON_LAZY_IMPORTS 模式。阅读相关的 test_shutil 覆盖情况和链接的 PRs,以了解当前方向。当不支持的 bz2 检查在 lazy_imports=all 下行为正确,且不会导致现有 shutil 测试回归时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。