A command-line tool that imports everything at the top of the file pays for all of it on every run, even for --help. Python 3.15, released on October 9, 2026, adds a lazy soft keyword (PEP 810). Your imports stay at the top of the file, but each module loads only when code first uses it.
This guide takes a small CLI, measures what its startup pays for, makes the imports lazy and measures again. It then covers the two ways lazy imports change behaviour: when errors appear, and when import-time side effects run.
1. Get Python 3.15
python3 --versionPython 3.15.2Any 3.15 release has the keyword. Older versions reject lazy import with a SyntaxError. Step 8 shows a form that works on both.
2. A CLI that imports everything up front
ops.py has three subcommands, and each one needs a different part of the standard library:
"""ops: a small admin CLI."""
import argparse
import asyncio
import http.server
import tarfile
import urllib.request
from pathlib import Path
VERSION = "1.4.0"
def check(urls):
def status(url):
req = urllib.request.Request(url, method="HEAD")
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.status
async def run():
codes = await asyncio.gather(*(asyncio.to_thread(status, u) for u in urls))
for url, code in zip(urls, codes):
print(code, url)
asyncio.run(run())
def serve(port):
handler = http.server.SimpleHTTPRequestHandler
with http.server.ThreadingHTTPServer(("127.0.0.1", port), handler) as httpd:
print(f"serving on http://127.0.0.1:{port}")
httpd.serve_forever()
def backup(src):
out = Path(f"{src}.tar.gz")
with tarfile.open(out, "w:gz") as tar:
tar.add(src)
print(f"wrote {out} ({out.stat().st_size} bytes)")
def main():
parser = argparse.ArgumentParser(prog="ops")
parser.add_argument("--version", action="version", version=f"ops {VERSION}")
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("check").add_argument("urls", nargs="+")
sub.add_parser("serve").add_argument("--port", type=int, default=8000)
sub.add_parser("backup").add_argument("src")
args = parser.parse_args()
if args.cmd == "check":
check(args.urls)
elif args.cmd == "serve":
serve(args.port)
else:
backup(args.src)
if __name__ == "__main__":
main()It works:
python3 ops.py backup notes
python3 ops.py check https://www.python.org https://peps.python.org/pep-0810/wrote notes.tar.gz (266 bytes)
200 https://www.python.org
200 https://peps.python.org/pep-0810/3. Measure what startup pays for
Time --version, which does no real work, and compare it with an empty interpreter. timeit runs each command 20 times per round and reports the best of 5 rounds:
python3 -m timeit -n 20 -r 5 -s "import subprocess" "subprocess.run(['python3', 'ops.py', '--version'], stdout=subprocess.DEVNULL)"
python3 -m timeit -n 20 -r 5 -s "import subprocess" "subprocess.run(['python3', '-c', 'pass'], stdout=subprocess.DEVNULL)"20 loops, best of 5: 70 msec per loop
20 loops, best of 5: 14.2 msec per loopPrinting a version string costs 56 ms more than starting Python. To see where the time goes, use -X importtime. It writes one line per module to stderr: the module's own time, then the cumulative time including everything it imported, in microseconds. The grep keeps only top-level imports:
python3 -X importtime ops.py --version 2> imports.log
grep -E '\| [a-z_]' imports.log | sort -t'|' -k2 -n | tail -6ops 1.4.0
import time: 299 | 1657 | site
import time: 865 | 3066 | urllib.request
import time: 736 | 5232 | argparse
import time: 10289 | 10289 | _colorize
import time: 470 | 11139 | http.server
import time: 204 | 25619 | asyncioasyncio alone takes 25.6 ms and http.server another 11 ms, and --version uses neither. Modules share dependencies, so the first module to load a shared one pays for it. On its own, http.server took about 19 ms on the same machine, but here asyncio had already loaded part of what it needs. Keep _colorize in mind for step 5.
Your numbers will differ by machine. Compare runs on the same machine and look at the ratio, not the absolute numbers.
4. Make the imports lazy
Put lazy in front of each import that only some commands need:
"""ops: a small admin CLI."""
import argparse
lazy import asyncio
lazy import http.server
lazy import tarfile
lazy import urllib.request
lazy from pathlib import Pathargparse stays eager because every run uses it. Nothing else in the file changes. Each lazy name starts out as a lightweight proxy. The first time code touches it, Python imports the module and swaps the proxy for the real object. From then on it behaves exactly like a normal import.
Run the same timeit command again:
20 loops, best of 5: 35.9 msec per loopStartup time dropped by half, from 70 ms to 35.9 ms. The import log confirms that the heavy modules never load:
python3 -X importtime ops.py --version 2> imports.log
grep -cE 'asyncio|http\.server|tarfile|urllib' imports.logops 1.4.0
0backup and check print the same output as before. Each module loads the first time its function runs.
5. Read what's left
Sort the new log and look at the top entries:
grep -E '\| [a-z_]' imports.log | sort -t'|' -k2 -n | tail -3import time: 367 | 1910 | shutil
import time: 775 | 4667 | argparse
import time: 7003 | 8465 | _colorize_colorize is the standard library's terminal colour module. argparse colours its output by default, and in 3.15 it loads _colorize through a lazy import of its own when it formats output. If plain help text is fine for your tool, turn colour off:
parser = argparse.ArgumentParser(prog="ops", color=False)20 loops, best of 5: 23.4 msec per loopThe same habit works in any app: make the obvious imports lazy, then sort the import log again and see what's left.
6. Errors now happen at first use
A failing lazy import doesn't fail on the import line. It fails where the name is first used:
lazy import yaml
print("started")
config = yaml.safe_load("debug: true")python3 missing.pystarted
Traceback (most recent call last):
File ".../missing.py", line 1, in <module>
lazy import yaml
ImportError: lazy import of 'yaml' raised an exception during resolution
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File ".../missing.py", line 4, in <module>
config = yaml.safe_load("debug: true")
^^^^
ModuleNotFoundError: No module named 'yaml'The traceback shows both the import line and the first use, so the cause is easy to find. The risk is timing. A missing dependency no longer stops the program at startup, so a deploy can look healthy until someone runs the one command that needs it. Make sure your tests cover every subcommand.
7. Side effects move too
Some modules do work when they're imported, such as registering a plugin. Delay the import and you delay the registration:
EXPORTERS = {}
def exporter(name):
def decorator(fn):
EXPORTERS[name] = fn
return fn
return decoratorfrom registry import exporter
@exporter("csv")
def to_csv(rows):
return "\n".join(",".join(map(str, row)) for row in rows)lazy import csv_export # registers the "csv" exporter
from registry import EXPORTERS
print(sorted(EXPORTERS))python3 report.py[]Nothing ever touches csv_export, so it never loads and the exporter is never registered. With a plain import csv_export, the output is ['csv']. Keep imports that exist only for their side effects eager.
8. Try it on a whole app without editing code
-X lazy_imports=all, or the PYTHON_LAZY_IMPORTS=all environment variable, makes every top-level import lazy unless a filter says otherwise. It's a quick way to see what an app could gain. Here it runs against the original, eager ops.py from step 2:
python3 -m timeit -n 20 -r 5 -s "import subprocess" "subprocess.run(['python3', '-X', 'lazy_imports=all', 'ops.py', '--version'], stdout=subprocess.DEVNULL)"20 loops, best of 5: 35.7 msec per loopIt also breaks the plugin example, even after changing report.py back to a plain import csv_export:
python3 -X lazy_imports=all report.py[]A filter function decides import by import. It receives the importing module's name, the imported module's name and the fromlist. Return False to force an eager import:
import sys
EAGER = {"csv_export"} # modules that must run at import time
def lazy_filter(importer, name, fromlist):
return name not in EAGER
sys.set_lazy_imports_filter(lazy_filter)
import csv_export # registers the "csv" exporter
from registry import EXPORTERS
print(sorted(EXPORTERS))python3 -X lazy_imports=all report_filtered.py['csv']Global mode also changes every library you depend on. Treat it as a measuring tool until your whole test suite passes with it turned on.
9. Support older Pythons with __lazy_modules__
A library that still supports Python 3.14 or earlier can't use the keyword. Instead it can list module names in __lazy_modules__. Python 3.15 treats plain imports of those modules as lazy. Older versions see an ordinary list that nothing reads:
import sys
__lazy_modules__ = ["tarfile"]
import tarfile
print(sys.version.split()[0], "tarfile loaded:", "tarfile" in sys.modules)
tarfile.TarFile
print(sys.version.split()[0], "tarfile loaded:", "tarfile" in sys.modules)python3 compat.py
python3.14 compat.py3.15.2 tarfile loaded: False
3.15.2 tarfile loaded: True
3.14.7 tarfile loaded: True
3.14.7 tarfile loaded: TrueChecking "name" in sys.modules is also the simplest way to see whether a lazy import has loaded yet.
10. Drop the TYPE_CHECKING block
Annotations are a good fit, because Python 3.14 and later evaluate them only when something reads them. If an import is used only in type hints, it never loads:
import sys
lazy from decimal import Decimal
def total(prices: list[Decimal]) -> Decimal:
return sum(prices)
print("decimal loaded:", "decimal" in sys.modules)
print(total.__annotations__)
print("decimal loaded:", "decimal" in sys.modules)decimal loaded: False
{'prices': list[decimal.Decimal], 'return': <class 'decimal.Decimal'>}
decimal loaded: TrueThat replaces the usual if TYPE_CHECKING: import block. The exception is code that reads annotations when a class is created. Put @dataclass on a class with a price: Decimal field and decimal loads as soon as the class is defined.
When not to use it
- Long-running servers. A server that starts once a day gains little from 30 ms. With eager imports, a missing dependency fails at boot, before any traffic arrives.
- Latency-sensitive first calls. The import cost doesn't disappear. It moves to the first use, so the first request that needs
asynciopays for loading it. - Imports kept for their side effects. Registration, monkeypatching and configuration on import all need an eager import.
- Code that must run on Python 3.14 or earlier. Use
__lazy_modules__instead of the keyword.
The best fit is a program that starts often and uses a different part of its imports each time, such as CLIs, test runners and serverless handlers.
Next steps
- Run
python3 -X importtimeon your own tool and sort by the cumulative column. - Run your test suite under
-X lazy_imports=allto find imports that rely on side effects. - Read PEP 810 for the full rules, including thread safety and import hooks.
- See What's new in Python 3.15 for the rest of the release, and the
-Xoptions reference forlazy_imports.