From ea90b032a016122e7871e91c5210f3b4e68768b4 Mon Sep 17 00:00:00 2001 From: Daniel Hollas Date: Mon, 2 Mar 2026 21:39:07 +0000 Subject: [PATCH] gh-117865: Speedup import of `inspect` module (#144756) Co-authored-by: Alex Waygood --- Lib/inspect.py | 8 ++++---- Lib/test/test_inspect/test_inspect.py | 9 +++++++++ .../2026-02-12-17-56-17.gh-issue-117865.jE1ema.rst | 1 + 3 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-02-12-17-56-17.gh-issue-117865.jE1ema.rst diff --git a/Lib/inspect.py b/Lib/inspect.py index 5d8ebb3dd540..dfc5503dee53 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -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(): diff --git a/Lib/test/test_inspect/test_inspect.py b/Lib/test/test_inspect/test_inspect.py index 4ad32c649ea8..68ea62f565d8 100644 --- a/Lib/test/test_inspect/test_inspect.py +++ b/Lib/test/test_inspect/test_inspect.py @@ -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 index 000000000000..f45f6682869e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-02-12-17-56-17.gh-issue-117865.jE1ema.rst @@ -0,0 +1 @@ +Reduce the import time of :mod:`inspect` module by ~20%. -- 2.47.3