← Back to blog
/ARTICLE

Python 3.15 Lazy Imports: Measure Startup Gains and Catch Compatibility Problems

Build an eager baseline, measure first use, and test the initialization behavior that lazy imports can change.

Blue and gold snake-inspired ribbons beside a stopwatch and illuminated modular blocks on a dark background.

Your CLI needs to print a help message. Before it does, it imports the reporting backend, which imports more modules, which initialize code the user never asked to run.

Python 3.15 lazy imports give you a direct way to defer that work. The interesting question is how much your actual command benefits—and whether delayed initialization changes its behavior.

This walkthrough shows how to build an eager baseline, measure startup and first use separately, and catch compatibility problems before rollout. It makes no claim about a universal speedup or results from an unperformed benchmark.

Understand what moves out of startup

Python 3.15 adds explicit lazy imports through PEP 810. You can write lazy import package or lazy from package import function at module scope. Python binds a proxy and waits until the imported name is used before loading the module.

That changes the timing of work. A command that never uses a reporting dependency can avoid loading it entirely. A command that immediately generates a report still needs that dependency. Its first use becomes part of the latency you must measure.

The feature is opt-in under the default configuration. Adding one lazy import does not automatically make the imported module’s dependencies lazy. Existing eager imports elsewhere can also load the same module before your lazy binding is used.

The language reference documents the syntax restrictions: explicit lazy imports belong at module scope, outside function and class bodies and outside try/except/finally blocks. Star imports and future imports cannot be marked lazy.

For this walkthrough, the goal is deliberately narrow: determine whether postponing one optional feature improves a useful command without breaking that feature.

Build two comparable entry points

Use a disposable directory and a CPython 3.15 interpreter. The examples need only the standard library. Replace python3.15 with your environment’s interpreter path if necessary, and record its exact version:

python3.15 -VV

Create report_backend.py:

import decimal
import statistics


def summarize():
    values = [decimal.Decimal("10.5"), decimal.Decimal("20.5")]
    return str(statistics.mean(values))

Create cli_eager.py:

import sys
import report_backend


def main():
    command = sys.argv[1] if len(sys.argv) > 1 else "help"
    if command == "report":
        print(report_backend.summarize())
    elif command == "help":
        print("Commands: help, report")
    else:
        raise SystemExit("Unknown command")


if __name__ == "__main__":
    main()

Copy that file to cli_lazy.py and change only its backend import:

lazy import report_backend

Run both paths in both files:

python3.15 cli_eager.py help
python3.15 cli_lazy.py help
python3.15 cli_eager.py report
python3.15 cli_lazy.py report

The intended functional behavior is the same: help displays the command list; report prints 15.5. These are expected outputs, not a record of Python 3.15 execution here. This article supplies a reproducible evaluation procedure rather than measured startup results.

The backend is intentionally modest. There is no artificial sleep masquerading as an import optimization. After checking the mechanics, substitute a real optional dependency from your application. Keep its version and configuration identical across both entry points.

Profile imports before timing the command

Use Python’s import-time diagnostic option:

python3.15 -X importtime cli_eager.py help 2> eager-imports.txt
python3.15 -X importtime cli_lazy.py help 2> lazy-imports.txt
python3.15 -X importtime cli_lazy.py report 2> report-imports.txt

Inspect whether the backend disappears from the unused-feature path and appears when the report actually runs. If another dependency already imports it, your selected statement might offer little benefit.

Treat this output as a map of where imports cost time. Do not add every cumulative column together: nested imports would be counted repeatedly. Also keep profiling separate from final timing, because instrumentation changes the workload.

A short import list is useful evidence about execution. It does not establish that the command is meaningfully faster for a user. For that, measure the process.

Measure fresh processes and retain the samples

Repeatedly importing inside one interpreter mostly measures an already populated module cache. Instead, launch a fresh child process for each sample. Save this as bench.py beside the CLI files:

import json
import os
from pathlib import Path
import random
import statistics
import subprocess
import sys
import time

root = Path(__file__).resolve().parent
cases = [(file, command)
         for file in ("cli_eager.py", "cli_lazy.py")
         for command in ("help", "report")]
samples = {f"{file}:{command}": [] for file, command in cases}
env = dict(os.environ, PYTHON_LAZY_IMPORTS="normal")


def run(file, command):
    started = time.perf_counter_ns()
    subprocess.run(
        [sys.executable, "-X", "lazy_imports=normal", file, command],
        cwd=root, env=env, check=True,
        stdout=subprocess.DEVNULL,
    )
    return (time.perf_counter_ns() - started) / 1_000_000


for case in cases:
    run(*case)  # discarded warm-up

rng = random.Random(42)
for _ in range(30):
    order = cases.copy()
    rng.shuffle(order)
    for file, command in order:
        samples[f"{file}:{command}"].append(run(file, command))

result = {"python": sys.version, "executable": sys.executable,
          "samples_ms": samples}
(root / "samples.json").write_text(json.dumps(result, indent=2))
for name, values in samples.items():
    print(name, "median_ms=", round(statistics.median(values), 3))

Run it with the same interpreter:

python3.15 bench.py

The harness uses subprocess.run with check=True, so a failed command stops the experiment. Its performance counter measures elapsed wall time, including process creation and shutdown. The reported median summarizes samples; the JSON preserves the evidence behind it.

Here, normal neutralizes an inherited global all setting while preserving the explicit lazy statement. It does not force every import eager. The baseline comes from the separate eager file.

Thirty samples are a starting point, not a statistical guarantee. Interleave cases to reduce drift, close unrelated workloads, and repeat the batch if differences are small. Record operating system, hardware, dependency lockfile, power mode, and environment settings alongside the JSON.

These are fresh-process measurements with warmed filesystem and bytecode caches. They are not cold-machine or cold-container measurements. If deployment cold starts are the concern, test the deployment lifecycle separately.

Read the result without overselling it

Compare eager help with lazy help, then eager report with lazy report. Calculate improvement as (eager_median - lazy_median) / eager_median * 100, and report the absolute difference too. A percentage without milliseconds can make a tiny change sound impressive.

If help improves but report remains similar, the change may still serve users who mostly run lightweight commands. If the report gets slower, quantify that cost before accepting the trade. If both paths barely change, choose a different candidate or stop optimizing imports.

For a web service, process completion is the wrong boundary. Measure time until the service is ready, the first request that touches the deferred feature, and subsequent requests. For a worker, include its first relevant task. Otherwise, startup work can simply move into the first customer’s request or job.

Define an acceptable first-use budget before seeing results. That keeps a pleasing startup number from deciding the entire rollout.

Catch compatibility problems through behavior

The most useful compatibility test checks an observable contract. Importing the entry point successfully is insufficient when the dependency has not executed yet.

PEP 810’s migration discussion highlights import-time side effects, especially registries. Consider this deliberately broken example:

# registry.py
handlers = {}
# plugin.py
import registry
registry.handlers["report"] = lambda: "ready"
# check_plugin.py
import registry
lazy import plugin
assert "report" in registry.handlers

In an isolated fresh process under normal lazy-import mode, that assertion is expected to fail: nothing uses plugin, so its registration has not happened. Run python3.15 check_plugin.py to exercise the case. Keeping import plugin eager is the smallest repair when registration is required immediately. A larger redesign can expose an explicit initialization function and call it during startup.

Use the same idea for your real system: assert that required commands, handlers, models, and tasks exist before readiness. Do not infer framework compatibility from this toy example; exercise the actual framework and dependency versions you deploy.

Add failure-path checks too. In a disposable environment, remove an optional dependency and invoke the feature that needs it. Confirm that the error is understandable and appears at the intended boundary. Keep ordinary function-local imports when you need to catch an optional import error locally; the new syntax does not belong inside that try block.

Finally, run your formatter, linter, type checker, packaging, and test collection against the changed source. An interpreter upgrade does not upgrade every parser in the toolchain. A passing unit test suite can still miss a rarely used command, so include direct smoke tests of deferred features.

Keep older Python support deliberate

A version guard cannot hide lazy import syntax from an older parser. If one source file must also run on older Python versions, the documented alternative is:

__lazy_modules__ = {"report_backend"}
import report_backend

Python 3.15 uses the declaration to select lazy imports; older versions retain ordinary import behavior. Use fully qualified module names, and define the declaration before the affected imports. Test the oldest supported interpreter as well as 3.15.

Avoid starting with global -X lazy_imports=all. It expands the compatibility surface beyond your selected statement. Begin with one optional feature, preserve required initialization, and compare the same useful behaviors before and after.

Ship the change when it produces a repeatable benefit for a real workload, keeps first use within budget, and passes the registration and failure-path checks. If those conditions do not hold, an eager import remains a perfectly reasonable engineering decision.