gh-154675: Use lazy imports in pdb, bdb, code - #156567
Conversation
| import _pyrepl.utils | ||
| except ModuleNotFoundError: | ||
| _pyrepl = None | ||
| lazy import _colorize |
There was a problem hiding this comment.
Hmm, this is now different to the other files, where we have lazy imports directly after the regular imports.
There was a problem hiding this comment.
The isort/ruff rule is:
import a
from b import c
lazy import d
lazy from e import fAnd this is following that, except I left the spaces between groups, but can remove those if you like?
|
I think making some import lazy definitely makes sense. Making |
|
I ran: pip install tuna
./python.exe -X importtime -c "import pdb" 2> import.log
tuna import.logThis gives the blue diagram to visualise the import times. Then looked at the slowest imports, and made them lazy one by one. Some would gett reified right away, like Others like The tests ensure that a lazy import doesn't end up getting immediately reified due to some other change. If that happens down the line, we can either do something to ensure it remains lazy, or make a conscious decision to allow it be eager, and update the test. We also have some deferred imports, like |
The goal here is to the improve import time of
pdb, one of the slowest stdlib modules to import.Before: 52 ms
mainon macOS with optimised build:After: 9 ms
We can lazily import several dependencies, and also do the same in its dependencies
bdbandcodeto make them lighter:pdb.set_trace()(orbreakpoint()with defaults) is commonly used for this module, and will reify 6 of the 18 lazy imports here, and the other 12 remain deferred.And
pdbis often imported without runningset_trace(), so we get the benefit of all 18 lazy imports.This also speeds up every pytest invocation, not just
pytest --pdb: pytest unconditionally importspdbat startup via its default debugging plugin. The pytest project found deferring import ofpdbsaved ~7% of pytest startup on Python 3.14 (pytest-dev/pytest#14874), but the change was declined in favour of improving import time in CPython itself.