◐ Shell
reader mode source ↗
Skip to content

gh-117865: Speedup import of inspect module#144756

Merged
hugovk merged 8 commits into
python:mainfrom
danielhollas:speedup-inspect-import-lazy
Mar 2, 2026
Merged

gh-117865: Speedup import of inspect module#144756
hugovk merged 8 commits into
python:mainfrom
danielhollas:speedup-inspect-import-lazy

Conversation

@danielhollas

@danielhollas danielhollas commented Feb 12, 2026

Copy link
Copy Markdown
Contributor

This is a revived version of #119526 (with Alex's blessing), using the new fancy lazy import machinery to defer imports of re and tokenize modules, for a ~20% speedup.

Before

image
hyperfine -w 5 "./python -c 'import inspect'"
Benchmark 1: ./python -c 'import inspect'
  Time (mean ± σ):      19.2 ms ±   1.9 ms    [User: 14.4 ms, System: 4.5 ms]
  Range (min … max):    16.3 ms …  23.4 ms    152 runs

After

image
hyperfine -w 5 "./python -c 'import inspect'"
Benchmark 1: ./python -c 'import inspect'
  Time (mean ± σ):      16.4 ms ±   2.0 ms    [User: 12.3 ms, System: 3.9 ms]
  Range (min … max):    13.8 ms …  22.2 ms    191 runs

Part of #137855

AlexWaygood and others added 3 commits February 12, 2026 17:01
While we can easily make ast import lazy in inspect module,
it is anyway imported in annotationlib, which cannot be made lazy.

@JelleZijlstra JelleZijlstra left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hide comment

Makes sense. re is used only in one place in formatannotation, so many users won't need it. tokenize is used a bit more heavily but most of the API in the module still won't need it.

@bedevere-app bedevere-app Bot added awaiting merge and removed labels Feb 13, 2026
@danielhollas

Copy link
Copy Markdown
Contributor Author

Hi all,

just a kind ping to see if this PR could be merged. 😊

Hide details View details @hugovk hugovk merged commit ea90b03 into python:main Mar 2, 2026
85 of 87 checks passed
@danielhollas danielhollas deleted the speedup-inspect-import-lazy branch March 2, 2026 22:31
ljfp pushed a commit to ljfp/cpython that referenced this pull request Apr 25, 2026
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants