]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-117865: Speedup import of `inspect` module (#144756)
authorDaniel Hollas <daniel.hollas@bristol.ac.uk>
Mon, 2 Mar 2026 21:39:07 +0000 (21:39 +0000)
committerGitHub <noreply@github.com>
Mon, 2 Mar 2026 21:39:07 +0000 (23:39 +0200)
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
Lib/inspect.py
Lib/test/test_inspect/test_inspect.py
Misc/NEWS.d/next/Library/2026-02-12-17-56-17.gh-issue-117865.jE1ema.rst [new file with mode: 0644]

index 5d8ebb3dd5400085f1436ce3d9444e6ee2317988..dfc5503dee536e9b8e5384da987c243a9b3a8062 100644 (file)
@@ -153,9 +153,9 @@ import importlib.machinery
 import itertools
 import linecache
 import os
-import re
+lazy import re
 import sys
-import tokenize
+lazy import tokenize
 import token
 import types
 import functools
@@ -163,9 +163,9 @@ import builtins
 from keyword import iskeyword
 from operator import attrgetter
 from collections import namedtuple, OrderedDict
-from weakref import ref as make_weakref
+from _weakref import ref as make_weakref
 
-# Create constants for the compiler flags in Include/code.h
+# Create constants for the compiler flags in Include/cpython/code.h
 # We try to get them from dis to avoid duplication
 mod_dict = globals()
 for k, v in dis.COMPILER_FLAG_NAMES.items():
index 4ad32c649ea83c41d035e12335d8ce73ba5f90b8..68ea62f565d8247810f7776db4da36cba56b953b 100644 (file)
@@ -173,6 +173,15 @@ class custom_descriptor:
         return self.func.__get__(instance, owner)
 
 
+class TestImportTime(unittest.TestCase):
+
+    @cpython_only
+    def test_lazy_import(self):
+        import_helper.ensure_lazy_imports(
+            "inspect", {"re", "tokenize"}
+        )
+
+
 class TestPredicates(IsTestBase):
 
     def test_excluding_predicates(self):
diff --git a/Misc/NEWS.d/next/Library/2026-02-12-17-56-17.gh-issue-117865.jE1ema.rst b/Misc/NEWS.d/next/Library/2026-02-12-17-56-17.gh-issue-117865.jE1ema.rst
new file mode 100644 (file)
index 0000000..f45f668
--- /dev/null
@@ -0,0 +1 @@
+Reduce the import time of :mod:`inspect` module by ~20%.