python / python/cpython

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

Open
#150,167 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

3.15 3.16 stdlib topic-lazy-imports type-bug
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.

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.