diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 394ba3a16a78d2..09d3f5103e7f9f 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1160,6 +1160,21 @@ Optimizations about 30% faster. (Contributed by Shamil Abdulaev in :gh:`158304`.) +* The import time for several standard library modules has been improved, + including + :mod:`argparse`, + :mod:`bdb`, + :mod:`code`, + :mod:`importlib`, + :mod:`pdb`, + :mod:`shutil`, + :mod:`unittest`, + :mod:`unittest.mock`, + and :mod:`xml.sax.saxutils`. + + (Contributed by Brett Cannon, Brittany Reynoso, Hugo van Kemenade, + Jelle van der Waa, Maxime David, and Savannah Ostrowski in :gh:`154675`.) + ast --- diff --git a/Lib/test/test_string/test_string.py b/Lib/test/test_string/test_string.py index 350784a9f00817..ce813508cc79d2 100644 --- a/Lib/test/test_string/test_string.py +++ b/Lib/test/test_string/test_string.py @@ -9,7 +9,7 @@ class LazyImportTest(unittest.TestCase): @cpython_only def test_lazy_import(self): - ensure_lazy_imports("base64", {"re", "collections"}) + ensure_lazy_imports("string", {"re", "collections"}) class ModuleTest(unittest.TestCase): diff --git a/Lib/test/test_unittest/test_loader.py b/Lib/test/test_unittest/test_loader.py index f4e50a3dccb2bc..c2e352fac3971a 100644 --- a/Lib/test/test_unittest/test_loader.py +++ b/Lib/test/test_unittest/test_loader.py @@ -5,6 +5,9 @@ import unittest +from test.support import cpython_only +from test.support.import_helper import ensure_lazy_imports + class Test_TestLoader(unittest.TestCase): ### Basic object tests @@ -1537,6 +1540,37 @@ class Foo(unittest.TestCase): self.assertEqual(loader.getTestCaseNames(Foo), test_names) +class TestLazyImports(unittest.TestCase): + @cpython_only + def test_lazy_imports(self): + ensure_lazy_imports( + "unittest", + { + "argparse", + "difflib", + "fnmatch", + "inspect", + "io", + "pprint", + "re", + "signal", + "traceback", + "warnings", + }, + ) + + def test_valid_module_name(self): + # Compiled on first access, via the module's __getattr__. + from unittest import loader + + pattern = loader.VALID_MODULE_NAME + self.assertIs(pattern, loader.VALID_MODULE_NAME) + self.assertTrue(pattern.match("test_spam.py")) + self.assertIsNone(pattern.match("1spam.py")) + with self.assertRaises(AttributeError): + loader.NO_SUCH_NAME + + class TestObsoleteFunctions(unittest.TestCase): class MyTestSuite(unittest.TestSuite): pass diff --git a/Lib/test/test_unittest/testmock/testmock.py b/Lib/test/test_unittest/testmock/testmock.py index ffc89dc5ce1562..6ee32faaf8b38e 100644 --- a/Lib/test/test_unittest/testmock/testmock.py +++ b/Lib/test/test_unittest/testmock/testmock.py @@ -3,7 +3,8 @@ import sys import tempfile -from test.support import ALWAYS_EQ +from test.support import ALWAYS_EQ, cpython_only +from test.support.import_helper import ensure_lazy_imports import unittest from test.test_unittest.testmock.support import is_instance from unittest import mock @@ -58,6 +59,22 @@ class Typos(): def something(a): pass +class LazyImportTest(unittest.TestCase): + @cpython_only + def test_lazy_import(self): + ensure_lazy_imports( + "unittest.mock", + { + "annotationlib", + "dataclasses", + "inspect", + "io", + "pkgutil", + "pprint", + }, + ) + + class MockTest(unittest.TestCase): def test_all(self): diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py index a392238c85abfa..39fa06d610c913 100644 --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -2,15 +2,15 @@ import sys import functools -import difflib -import pprint -import re -import warnings import collections import contextlib -import traceback import time import types +lazy import difflib +lazy import pprint +lazy import re +lazy import traceback +lazy import warnings from . import result from .util import (strclass, safe_repr, _count_diff_all_purpose, diff --git a/Lib/unittest/loader.py b/Lib/unittest/loader.py index 697520246f0e3c..f1770e6d7fddd0 100644 --- a/Lib/unittest/loader.py +++ b/Lib/unittest/loader.py @@ -1,23 +1,29 @@ """Loading unittests.""" -import inspect import os -import re import sys -import traceback import types import functools +lazy import inspect +lazy import re +lazy import traceback -from fnmatch import fnmatch, fnmatchcase +lazy from fnmatch import fnmatch, fnmatchcase from . import case, suite, util __unittest = True -# what about .pyc (etc) -# we would need to avoid loading the same tests multiple times -# from '.py', *and* '.pyc' -VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE) +def __getattr__(name): + if name == "VALID_MODULE_NAME": + # Compiled on first use so that importing unittest doesn't import re. + global VALID_MODULE_NAME + # what about .pyc (etc) + # we would need to avoid loading the same tests multiple times + # from '.py', *and* '.pyc' + VALID_MODULE_NAME = re.compile(r"[_a-z]\w*\.py$", re.IGNORECASE) + return VALID_MODULE_NAME + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") class _FailedTest(case.TestCase): @@ -422,7 +428,7 @@ def _find_test_path(self, full_path, pattern, namespace=False): """ basename = os.path.basename(full_path) if os.path.isfile(full_path): - if not VALID_MODULE_NAME.match(basename): + if not sys.modules[__name__].VALID_MODULE_NAME.match(basename): # valid Python identifiers only return None, False if not self._match_path(basename, full_path, pattern): diff --git a/Lib/unittest/main.py b/Lib/unittest/main.py index 850c825a736657..ce3a48363c3b65 100644 --- a/Lib/unittest/main.py +++ b/Lib/unittest/main.py @@ -1,8 +1,8 @@ """Unittest main program""" import sys -import argparse import os +lazy import argparse from . import loader, runner from .signals import installHandler diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index d3d47ff81e8596..66d3dc15084de0 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -25,20 +25,20 @@ import contextlib -import io -import inspect -import pprint import sys import builtins -import pkgutil -from inspect import iscoroutinefunction import threading -from annotationlib import Format -from dataclasses import fields, is_dataclass from types import CodeType, LazyImportType, ModuleType, MethodType from unittest.util import safe_repr -from functools import wraps, partial +from functools import cache, wraps, partial from threading import RLock +lazy import inspect +lazy import io +lazy import pkgutil +lazy import pprint +lazy from annotationlib import Format +lazy from dataclasses import fields, is_dataclass +lazy from inspect import iscoroutinefunction class InvalidSpecError(Exception): @@ -2275,11 +2275,15 @@ def __get__(self, obj, _type=None): return self.create_mock() -try: - _CODE_SIG = inspect.signature(partial(CodeType.__init__, None)) - _CODE_ATTRS = dir(CodeType) -except ValueError: - _CODE_SIG = None +_CODE_ATTRS = dir(CodeType) + +@cache +def _get_code_sig(): + # Computed on first use to defer importing inspect + try: + return inspect.signature(partial(CodeType.__init__, None)) + except ValueError: + return None class AsyncMockMixin(Base): @@ -2292,10 +2296,10 @@ def __init__(self, /, *args, **kwargs): self.__dict__['_mock_await_count'] = 0 self.__dict__['_mock_await_args'] = None self.__dict__['_mock_await_args_list'] = _CallList() - if _CODE_SIG: + if code_sig := _get_code_sig(): code_mock = NonCallableMock(spec_set=_CODE_ATTRS) code_mock.__dict__["_spec_class"] = CodeType - code_mock.__dict__["_spec_signature"] = _CODE_SIG + code_mock.__dict__["_spec_signature"] = code_sig else: code_mock = NonCallableMock(spec_set=CodeType) code_mock.co_flags = ( diff --git a/Lib/unittest/result.py b/Lib/unittest/result.py index a787686a5bea4c..c5701584b3a414 100644 --- a/Lib/unittest/result.py +++ b/Lib/unittest/result.py @@ -1,8 +1,8 @@ """Test result object""" -import io import sys -import traceback +lazy import io +lazy import traceback from . import util from functools import wraps diff --git a/Lib/unittest/runner.py b/Lib/unittest/runner.py index f19d7b6e446d2a..bf603b9b596443 100644 --- a/Lib/unittest/runner.py +++ b/Lib/unittest/runner.py @@ -2,7 +2,7 @@ import sys import time -import warnings +lazy import warnings from . import result from .case import _SubTest diff --git a/Lib/unittest/signals.py b/Lib/unittest/signals.py index e6a5fc52439712..f3312d619f0b25 100644 --- a/Lib/unittest/signals.py +++ b/Lib/unittest/signals.py @@ -1,5 +1,5 @@ -import signal import weakref +lazy import signal from functools import wraps diff --git a/Misc/NEWS.d/next/Library/2026-11-30-14-24-34.gh-issue-154675.tU_Upw.rst b/Misc/NEWS.d/next/Library/2026-11-30-14-24-34.gh-issue-154675.tU_Upw.rst new file mode 100644 index 00000000000000..0e6b29cf02d99c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-30-14-24-34.gh-issue-154675.tU_Upw.rst @@ -0,0 +1,2 @@ +Improve import time of :mod:`unittest` and :mod:`unittest.mock` by around 4 +times. Patch by Hugo van Kemenade.