Importing `bz2` will succeed under `lazy_imports=all` even if bz2 is not supported
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
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.
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with Lib/shutil.py lines 21-26 and reproduce the two PYTHON_LAZY_IMPORTS modes on a CPython build without bz2 support. Read the related test_shutil coverage and the linked PRs to understand the current direction. Done means the unsupported-bz2 check behaves correctly under lazy_imports=all without regressing existing shutil tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100