Skip to content

Commit b98e1a5

Browse files
authored
gh-154904: Speed up import of shutil by probing compression extensions directly (#154908)
1 parent 219768f commit b98e1a5

3 files changed

Lines changed: 24 additions & 6 deletions

File tree

Lib/shutil.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,28 @@
1818
except ImportError:
1919
_ZLIB_SUPPORTED = False
2020

21+
# bz2, lzma and compression.zstd are pure Python wrappers whose only
22+
# importable dependency that may be missing is the extension module they
23+
# wrap. Probe those extensions directly instead: it gives the same answer
24+
# without executing the wrappers, which shutil only needs when an archive
25+
# is actually created or extracted.
2126
try:
22-
import bz2
23-
del bz2
27+
import _bz2
28+
del _bz2
2429
_BZ2_SUPPORTED = True
2530
except ImportError:
2631
_BZ2_SUPPORTED = False
2732

2833
try:
29-
import lzma
30-
del lzma
34+
import _lzma
35+
del _lzma
3136
_LZMA_SUPPORTED = True
3237
except ImportError:
3338
_LZMA_SUPPORTED = False
3439

3540
try:
36-
from compression import zstd
37-
del zstd
41+
import _zstd
42+
del _zstd
3843
_ZSTD_SUPPORTED = True
3944
except ImportError:
4045
_ZSTD_SUPPORTED = False

Lib/test/test_shutil.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from test import support
3333
from test.support import os_helper, socket_helper
3434
from test.support.os_helper import TESTFN, FakePath
35+
from test.support.import_helper import ensure_lazy_imports
3536

3637
TESTFN2 = TESTFN + "2"
3738
TESTFN_SRC = TESTFN + "_SRC"
@@ -2362,6 +2363,14 @@ def _boo(filename, extract_dir, extra):
23622363
unregister_unpack_format('Boo2')
23632364
self.assertEqual(get_unpack_formats(), formats)
23642365

2366+
def test_compression_wrappers_not_imported_by_shutil(self):
2367+
# gh-154904: Importing shutil must not pull in the compression
2368+
# wrappers: they are only needed once an archive is actually created
2369+
# or extracted, and importing them measurably slows down every
2370+
# process that uses shutil.
2371+
ensure_lazy_imports("shutil",
2372+
{"bz2", "lzma", "compression", "compression.zstd"})
2373+
23652374

23662375
class TestMisc(BaseTest, unittest.TestCase):
23672376

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Speed up :mod:`shutil` import by probing the ``_bz2``, ``_lzma`` and
2+
``_zstd`` extension modules instead of importing the :mod:`bz2`,
3+
:mod:`lzma` and :mod:`compression.zstd` wrappers, which are now only
4+
imported when an archive is actually created or extracted.

0 commit comments

Comments
 (0)