From 04a8f12067922c6faf5c1abdcc2fa35600a7d7d9 Mon Sep 17 00:00:00 2001 From: David C Ellis Date: Fri, 11 Sep 2026 14:27:38 +0100 Subject: [PATCH 1/2] Add a test for import failure under lazy_imports=all --- Lib/test/test_bz2.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Lib/test/test_bz2.py b/Lib/test/test_bz2.py index 64293d757331d75..c504b147dd538d5 100644 --- a/Lib/test/test_bz2.py +++ b/Lib/test/test_bz2.py @@ -1222,6 +1222,20 @@ def test_newline(self): self.assertEqual(f.readlines(), [text]) +class TestMissingModuleImport(unittest.TestCase): + # Test that module import fails if _bz2 is not available + # See: https://github.com/python/cpython/issues/150167 + @support.thread_unsafe("Modifies global import state") + def test_under_lazy_all(self): + import_state = sys.get_lazy_imports() + try: + sys.set_lazy_imports("all") + with self.assertRaises(ImportError): + import_helper.import_fresh_module("bz2", blocked=("_bz2",)) + finally: + sys.set_lazy_imports(import_state) + + def tearDownModule(): support.reap_children() From 131ae67bc7b2922c28b3bce83bfa4a8f54f9a092 Mon Sep 17 00:00:00 2001 From: David C Ellis Date: Mon, 27 Jul 2026 12:15:38 +0100 Subject: [PATCH 2/2] Force the eager import of `_bz2` inside `bz2.py` --- Lib/bz2.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/bz2.py b/Lib/bz2.py index eb58f4da596ea18..418f67c248047b4 100644 --- a/Lib/bz2.py +++ b/Lib/bz2.py @@ -14,6 +14,7 @@ import io import os +import _bz2; _bz2 # Force the eager import of _bz2 from _bz2 import BZ2Compressor, BZ2Decompressor