gh-154675: Use lazy imports in json package - #156801
Conversation
`argparse` and `_colorize` are only needed once `main()` runs, so import them lazily. Also hoist the nested `warnings._deprecated` import in `json.__getattr__` up to a module-level `lazy from`. `python -c "import json.tool"` drops from 41.1 ms to 21.2 ms (-48%): interleaved A/B, median of 9 rounds of min-of-25 runs, same binary with `Lib/json` swapped via `PYTHONPATH`; an unrelated `import csv` control moved +0.2%. Running the CLI is unchanged -- `main()` always builds an `ArgumentParser` and always calls `can_colorize()`, so both modules still get imported.
|
Are there any use cases where the improved import time matters? Users importing |
Don't think so. And |
|
AFAIR, the PEP explicitly said that we do not want to mechanically convert everything to lazy imports. Considering the noise for json itself I wonder about this change. json.tool is likely to be used as a CLI and there is no reason to do "import json.tool" as the public API is empty IIRC |
…q7vZ2.rst Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>
|
Solid call out. Dug in and I completely see what you mean... |
|
I'll close then 👍🏽 |
summary
Apply lazy imports to json package to lift nested imports and optimize the modules.
perf
python -c "import json.tool"python -c "import json"python -m json.tool f.json