Trending

World technology news

→
Python 3.15 lazy imports: Reducing startup time without breaking side effects
Software Engineering · 2026
Software Engineering

Python 3.15 lazy imports: Reducing startup time without breaking side effects

Test Python 3.15 explicit lazy imports in a command-line application while validating startup, first-use latency, import side effects, package compatibility and rollback.

Developer's JournalPublished: Dec 4, 20266 min read
Reading progress0%
In this article
  1. Separate the current patch from the feature milestone
  2. Measure startup and first useful work separately
  3. Turn import side effects into an explicit inventory
  4. Test compatibility across tools and threads
  5. Prepare a small pilot and a reversible rollout
  6. Four clean interpreter processes
  7. Specify which ordering the application needs

Separate the current patch from the feature milestone

Python 3.15.0 was released as stable on October 9, 2026, and the Python.org page now notes that it has been superseded by 3.15.2. Current deployment tests should therefore use 3.15.2, while the historical release event remains the 3.15.0 date. Hugo van Kemenade edited the What’s New document and signed the Python Insider release note from Rennes, France, within the Python Software Foundation ecosystem. PEP 810 is Final. In the default normal mode, ordinary imports keep their existing behavior; loading is deferred only when a developer explicitly selects the lazy keyword.

Measure startup and first useful work separately

A command-line tool may not need a heavy reporting package when the user asks only for --help. A lazy import can reduce startup time, but it moves cost to first use. Measure both time from process start to the help output and time to the first successful result of the real command. Use the same virtual environment, locked dependencies and warm or cold filesystem conditions for at least thirty runs. Record median and p95 values. Do not claim an overall improvement from a faster help path alone; first-use latency and peak memory belong in the acceptance criteria.

Database access flowConceptual sketch · summary of the article's technical flow
lazy import report_engine

def run_report(data):
    return report_engine.render(data)

Turn import side effects into an explicit inventory

Some packages register plugins, read environment variables, install warning filters or configure telemetry during import. Deferral changes when those effects occur. Before marking a module lazy, list its import-time behavior and decide whether first-use execution is safe. Do not delay a module that must install a security policy or signal handler during startup. Test observable outcomes rather than relying only on sys.modules: plugin lists, registered commands, log handlers and the first failure point. If an import error now appears at first use, make sure the error preserves enough context to identify the feature that triggered it.

Test compatibility across tools and threads

PEP 810 permits module-by-module adoption, but parsers, type checkers, packagers and test discovery must understand Python 3.15 syntax. If the minimum supported version is 3.14, the same source file cannot be parsed there; use a version-specific entry point or branch. Test the result when multiple threads first touch the same lazy name. Put plugin discovery, zip applications, frozen binaries and custom import hooks in a separate compatibility matrix. CI should distinguish 3.15.2 from supported older interpreters instead of letting one successful job hide a parser or packaging failure.

Prepare a small pilot and a reversible rollout

Start with one infrequently used dependency that has no required import side effects. Capture importtime output, resident memory, the help command and a real work command for the baseline. In the lazy version, test the path that never uses the module, first use, import failure and concurrent first access. Repeat after dependency upgrades because a later release may add import-time behavior. Reverting to a normal import is mechanically small, but retain measurements and deployment evidence. Broader rollout should require a p95 startup gain, acceptable first-use latency, identical outputs and no missing registrations.

Four clean interpreter processes

I ran the same task in separate Python processes so no earlier run could preload the report module. The module prints engine:registered when imported and returns report:three orders when called. The explicit lazy import left only cli:ready on the help path. The work path printed cli:ready first, then engine:registered and the report. In a separate source file using a normal import, even the help path printed engine:registered before cli:ready. A fourth process declared a lazy import of a nonexistent module, printed readiness and caught ModuleNotFoundError at its first use. The fixture measures when visible outcomes happen. I ran it with the official Windows 64-bit embeddable Python 3.15.2 package without a third-party Python library or external service. The printed sequence is not a timing benchmark. Each process starts from an independent module cache so the second attempt cannot pass by relying on the first one.

import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory


CLI = """import sys
sys.path.insert(0, sys.argv[1])
lazy import report_engine
print('cli:ready')
if sys.argv[2] == 'run':
    print(report_engine.render())
"""
MODULE = """print('engine:registered')
def render():
    return 'report:three orders'
"""
MISSING = """lazy import absent_fixture_module
print('cli:ready')
try:
    absent_fixture_module.render()
except ModuleNotFoundError as error:
    print('feature:' + error.name)
"""

with TemporaryDirectory() as directory:
    root = Path(directory)
    scripts = {
        'cli.py': CLI,
        'eager.py': CLI.replace('lazy import report_engine', 'import report_engine', 1),
        'report_engine.py': MODULE,
        'missing.py': MISSING,
    }
    for name, source in scripts.items():
        (root / name).write_text(source, encoding='utf-8')

    def run(script, *arguments, mode='normal'):
        result = subprocess.run(
            [sys.executable, '-X', f'lazy_imports={mode}', str(root / script), *arguments],
            env={k: v for k, v in os.environ.items() if k != 'PYTHON_LAZY_IMPORTS'},
            text=True, capture_output=True, check=True,
        )
        return result.stdout.splitlines()

    observed = {
        'help': run('cli.py', directory, 'help'),
        'first_use': run('cli.py', directory, 'run'),
        'eager_help': run('eager.py', directory, 'help'),
        'missing': run('missing.py'),
    }
    assert observed == {
        'help': ['cli:ready'],
        'first_use': ['cli:ready', 'engine:registered', 'report:three orders'],
        'eager_help': ['engine:registered', 'cli:ready'],
        'missing': ['cli:ready', 'feature:absent_fixture_module'],
    }
    print(sys.version.split()[0], observed)

Specify which ordering the application needs

Define what must finish before the program reports readiness. A mandatory plugin may have to register even on the help path. An optional report module can instead register at first use if the application can report errors there. The tested Windows interpreter accepts normal and all in its command-line help. In this build, the attempted -X lazy_imports=none invocation was rejected at process startup. The comparison therefore runs a separate file using the ordinary import statement, which also makes the change easy to review and reverse. Measure the help and real work paths independently in your production build. The example cannot establish concurrent first-use behavior or the overhead of external dependencies. It provides an observable test for each intended import sequence and shows where a missing optional dependency becomes a user-visible error.

110 reads ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.