diff --git a/Lib/bz2.py b/Lib/bz2.py index eb58f4da596ea1..418f67c248047b 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 diff --git a/Lib/test/test_bz2.py b/Lib/test/test_bz2.py index 64293d757331d7..c504b147dd538d 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()