Python 3.15's Lazy Imports: Make Your CLI 3x Faster
Working to Make Python Lazy
Python 3.15 introduces lazy imports, a feature that defers module loading until first use, significantly speeding up CLI applications and large codebases. The author, Henry Schreiner, explains the concept, shows how to use the new `lazy` keyword or the backward-compatible `__lazy_modules__` list, and introduces `flake8-lazy`, a tool he developed to automate adding lazy declarations. Real-world results show 2-4x speedups for `--help` in projects like cibuildwheel and repo-review. The post also covers edge cases, tips, and the author's positive experience using AI to develop the tool.
100+ ms is noticeable, getting under that makes your app feel snappier.
- mhashemi
I've got my reservations about lazy imports, but scipy in particular is such a memory hog, I've increasingly been vendoring smaller utilities out of it. Good lazy imports would be a big help.
- dataflow
> This pattern, for example, can’t be lazy: try: import numpy; except ModuleNotFoundError: ...
Wait, that seems bad. These kinds of modules (especially numba) are often exactly the ones that you want to delay importing. Why not provide a way to check the existence at import time? How are you supposed to handle nonexistence in that case?
- yuriks
This feature seems really valuable for commandline tools! However this paragraph gave me pause:
> Currently, disabling lazy imports disabled the syntax keyword, which means that you can’t use it for circular imports, type checking, etc.
Imo this is a good thing, laziness shouldn't be semantically important. The ability to force disable laziness while maintaining semantics is important for linting and testing, and more often than not, circular imports are a sign of bad code structure.