Skip to content

gh-117865: Speedup import of inspect module#144756

Open
danielhollas wants to merge 8 commits intopython:mainfrom
danielhollas:speedup-inspect-import-lazy
Open

gh-117865: Speedup import of inspect module#144756
danielhollas wants to merge 8 commits intopython:mainfrom
danielhollas:speedup-inspect-import-lazy

Conversation

@danielhollas
Copy link
Contributor

@danielhollas danielhollas commented Feb 12, 2026

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.
Lib/inspect.py Outdated
from weakref import ref as make_weakref
from _weakref import ref as make_weakref

lazy import re
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Not sure about the convention here: where do we put lazy imports?

Copy link
Member

Choose a reason for hiding this comment

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

My intuition would be that you put them in the same place you'd have put them before, just with "lazy" in front.

(Yay, a new thing to argue about! I guess isort will have to make the decision for us in the future.)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks, yeah I put them back, it also made the diff nicer. (currently there doesn't seem to be consistent sorting in stdlib anyway)

Copy link
Member

@JelleZijlstra JelleZijlstra left a comment

Choose a reason for hiding this comment

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

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants