CodeSapient
← All articles

Python Lazy Imports in 3.15: Faster CLI and Django Startup

Python 3.15's lazy imports (PEP 810) load a module on first use. Lab-tested on a CLI and Django 6.1: how to find slow imports, what we measured, and what can break.

By CodeSapient Labs ·
Manila 80-column punched card on a green desk blotter, keypunched with LAZY IMPORT BOTO3, with a printed panel reading Lazy Imports and a punched bar chart comparing 288 ms eager startup with 22 ms lazy

Our internal opscli tool has a version command that prints one line. It took 288 ms to run. A bare Python 3.15 interpreter starts in 11 ms, so almost all of that time went to imports: boto3, pydantic, rich, jinja2 and requests, all loaded at the top of the file and none of them needed to print a version string. The same tax hits every Django management command, cron job, Celery beat process and serverless cold start that imports more than it uses.

Python 3.15, released on 9 October 2026, adds Python lazy imports as a language feature (PEP 810). You write lazy import boto3, the name is bound to a placeholder, and the module only loads when your code first touches it. With that change and one small refactor, the same version command ran in 22 ms. This guide shows how the feature works, how to find the imports worth deferring, what we measured on a CLI and a Django 6.1 project, and the behaviour changes that can break code that relies on import side effects.

What lazy imports change

A normal import finds the module, runs all of its top-level code and binds the result to a name before the next line runs. A lazy import skips the loading step. It binds the name to a proxy object of type types.LazyImportType and records the module name in sys.lazy_modules. The first time your code uses that name, Python performs the real import and swaps the proxy for the real module. PEP 810 calls this step reification.

import sys

lazy import json
lazy from decimal import Decimal

print("json loaded?", "json" in sys.modules)        # False
print("json pending?", "json" in sys.lazy_modules)  # True

price = Decimal("19.99")                            # decimal loads here
print(json.dumps({"price": str(price)}))            # json loads here
print("json loaded?", "json" in sys.modules)        # True

The keyword works for both forms:

  • lazy import boto3 defers the whole module.
  • lazy from jinja2 import Template binds Template to a proxy. Using it loads jinja2 and resolves only that name.
  • lazy is a soft keyword. Existing variables called lazy keep working.

After the first use, the name refers to the real module and behaves exactly like an eager import. Once a module is loaded, the remaining cost is a check that, according to PEP 810, the interpreter's adaptive specialization removes after a few accesses.

Find the imports that cost you startup time

Don't add lazy everywhere. Measure first. Python's -X importtime option prints the time spent importing every module. Its output is long, so we use a short script that lists only the top-level imports, with modules loaded during interpreter startup filtered out:

"""List the imports that cost a Python program the most startup time.

Usage: python slowest_imports.py path/to/script.py [args...]
"""
import subprocess
import sys


def import_times(args):
    """Return (cumulative_us, indent, module) rows from -X importtime."""
    proc = subprocess.run([sys.executable, "-X", "importtime", *args],
                          capture_output=True, text=True)
    rows = []
    for line in proc.stderr.splitlines():
        if not line.startswith("import time:") or "cumulative" in line:
            continue
        _, cumulative, name = line.split("|")
        indent = len(name) - len(name.lstrip())
        rows.append((int(cumulative), indent, name.strip()))
    return rows


baseline = {name for _, _, name in import_times(["-c", "pass"])}  # interpreter startup
rows = [r for r in import_times(sys.argv[1:]) if r[2] not in baseline]
top_level = min(indent for _, indent, _ in rows)
direct = [(us, name) for us, indent, name in rows if indent == top_level]

for us, name in sorted(direct, reverse=True)[:10]:
    print(f"{us / 1000:8.1f} ms  {name}")

Run against the eager version of our CLI, it printed:

$ python slowest_imports.py opscli_eager.py version
   105.8 ms  boto3
    16.1 ms  requests
    14.9 ms  rich.console
    14.8 ms  pydantic
    13.5 ms  jinja2
    12.3 ms  pydantic.fields
     9.1 ms  pydantic._internal._model_construction

-X importtime adds its own overhead, so read these numbers as relative costs, not exact timings. The shape is what matters. One SDK took more time than everything else together, and a run that doesn't touch S3 still paid for it. Notice also the pydantic.fields and pydantic._internal lines: those modules were loaded while a class body ran at import time, which turns out to be important.

Three ways to turn lazy imports on

1. The lazy keyword

This is the explicit option, and the one to use for your own code on Python 3.15 and later. The imports stay at the top of the file:

import argparse
import sys

lazy import boto3
lazy import requests
lazy from jinja2 import Template
lazy from pydantic import BaseModel
lazy from rich.console import Console

The keyword is only allowed at module level. We confirmed on 3.15.2 that each of these is a SyntaxError:

  • lazy import inside a function ("lazy import not allowed inside functions")
  • inside a class body
  • inside a try/except block, so the common try: import ujson except ImportError: import json fallback has to stay eager
  • lazy from module import * and lazy from __future__ import ...

Python 3.14 and older can't parse the keyword at all. A file that uses it fails with SyntaxError: invalid syntax before any of your code runs.

2. __lazy_modules__ for code that also runs on older Pythons

If a library or service still supports 3.14, define __lazy_modules__ at the top of the module. On 3.15 the listed imports become lazy. Older versions ignore the variable and import eagerly:

import sys
__lazy_modules__ = {"decimal"}
import decimal

print(sys.version.split()[0], "decimal loaded at import:", "decimal" in sys.modules)
decimal.Decimal("1.10")
print("after use:", "decimal" in sys.modules)

We ran the same file on both versions. Python 3.15.2 printed decimal loaded at import: False. Python 3.14.10 printed True and otherwise ran normally. Our __lazy_modules__ variant of the CLI took 109 ms on 3.15, the same as the keyword variant.

3. A global switch, with a filter

You can make every eligible import lazy without editing any source, with python -X lazy_imports=all or PYTHON_LAZY_IMPORTS=all. That includes imports inside every third-party package you use. The default mode is normal, which only honours the keyword and __lazy_modules__.

One detail differs from the PEP text. PEP 810 describes a third mode, none, that forces everything eager. On the 3.15.2 build we tested, sys.set_lazy_imports('none') raised ValueError: mode must be 'normal' or 'all', and the -X option accepted only the same two values. The What's New in Python 3.15 page also lists only those two. To keep specific modules eager, use a filter instead:

import sys

# Modules that must run at startup because importing them has side effects.
MUST_BE_EAGER = {"plugin_csv"}


def lazy_filter(importing, imported, fromlist):
    return imported not in MUST_BE_EAGER


sys.set_lazy_imports_filter(lazy_filter)
sys.set_lazy_imports("all")

import plugin_csv  # noqa: F401  filter says no -> eager, registers itself
import decimal     # lazy under "all"
from plugins_registry import PLUGINS

print("registered plugins:", sorted(PLUGINS))
print("decimal loaded yet:", "decimal" in sys.modules)

The filter receives the importing module's name, the imported module's name and the fromlist. Returning False forces that import to be eager. This script printed registered plugins: ['csv'] and decimal loaded yet: False.

What we measured on a CLI

We built four variants of the same opscli script with argparse and four subcommands, and ran each command 30 times on Python 3.15.2 with boto3 1.44, pydantic 2.14, rich, Jinja2 and requests. Times are median wall-clock times for the whole process.

Punched-card style bar chart: opscli version command takes 288 ms eager, 109 ms with -X lazy_imports=all, 113 ms with the lazy keyword and 22 ms after moving the pydantic model; report and validate commands shown the same way
Each punched slot is 5 ms. Measured on one Linux machine on 4 December 2026; your numbers will differ.
  • Eager: version 288 ms, 624 modules loaded, 53 MB peak RSS.
  • Lazy keyword on all five imports: 113 ms, 201 modules. Better, but not as good as expected.
  • Lazy keyword plus one refactor: 22 ms, 82 modules, 16 MB peak RSS.
  • Eager source with -X lazy_imports=all: 109 ms, 172 modules.

Why the first lazy version stalled at 113 ms

The CLI defined its pydantic model at module level:

lazy from pydantic import BaseModel


class Order(BaseModel):   # runs at import time and uses BaseModel
    id: int
    total: float

A class statement runs when the module loads, and using BaseModel as a base class is a use of the name. So pydantic was loaded on every run, including version. The -X lazy_imports=all run hit the same wall for the same reason. The fix was to move the model into its own module and import that lazily:

# models.py
from pydantic import BaseModel


class Order(BaseModel):
    id: int
    total: float


# opscli.py
lazy from models import Order

The same applies to anything that runs at module level: decorators from a lazily imported library, module-level constants built from it, or a default argument that calls into it. If sys.modules still contains a module you marked lazy right after startup, something at module level used it.

The cost moves, it doesn't disappear

Commands that need a library still pay for it. validate needs pydantic, so it stayed at about 110 ms in every lazy variant. report dropped from 296 ms to 79 ms because it only loads Jinja2 and rich. The s3client command, which creates a boto3 client, went from 393 ms eager to 277 ms with the fixed lazy version. (We measured that command separately with the EC2 metadata lookup disabled and dummy credentials, because boto3's credential search added about two seconds that had nothing to do with imports.) The gain comes from not loading what a given run doesn't use.

What happened with Django

We created a small Django 6.1.4 project with one app containing a model, an admin registration, a post_save signal connected in AppConfig.ready(), a JSON view and two tests. Without changing any source, we ran it under -X lazy_imports=all. check, migrate and the test suite (which checks that the signal fired and the admin registration exists) passed in both modes. Median of 20 runs:

Punched-card style bar chart for a Django 6.1 project: manage.py check 256 ms by default vs 178 ms with lazy_imports=all, manage.py help 236 vs 158 ms, first WSGI response 177 vs 124 ms, and 633 vs 410 modules loaded
One small project, not a production codebase. Large projects with many apps will behave differently.
  • manage.py check: 256 ms by default, 178 ms with lazy_imports=all.
  • manage.py help: 236 ms vs 158 ms.
  • Importing the WSGI app and serving one request: 177 ms vs 124 ms, with 633 vs 410 modules loaded afterwards.

The signal worked because Django's usual pattern imports signals.py inside the ready() method. Imports inside functions are never lazy, so that import still runs at startup. The WSGI numbers show the trade-off for web servers. In the default mode, importing shop.wsgi took 173 ms. In all mode the import took no measurable time, and the loading happened during the first request instead. For a CLI or a scale-to-zero function, that is usually what you want. For a long-running web worker, the first user after a deploy pays the cost, and nothing has been loaded before the server forks its workers. We didn't test Gunicorn's --preload or memory sharing between workers, so measure that before you enable all on a web tier.

If you run Django in containers, the same startup cost shows up in every migration job, management command and health check. Our guide to running Django in Docker in production covers the rest of that setup, and our post on AWS Lambda web functions covers cold starts, where import time is often the largest part.

Behaviour changes that can break your code

Imports kept only for their side effects

Plugin systems, Celery task modules, model registries and signal handlers often rely on importing a module to register something. A lazy import of such a module never runs it:

# plugin_csv.py
from plugins_registry import register


@register("csv")
def export_csv(rows):
    return "\n".join(",".join(map(str, r)) for r in rows)


# main.py
# Import-time side effects: a plugin that registers itself on import.
lazy import plugin_csv  # noqa: F401  imported only for its side effect
from plugins_registry import PLUGINS

print("registered plugins:", sorted(PLUGINS))

This printed registered plugins: []. Changing the first line back to a plain import printed ['csv']. Running that plain-import version under -X lazy_imports=all printed [] again. That is the main risk of the global switch: it silently changes imports you didn't write. Keep such modules eager with the filter shown above, or import them inside a startup function.

Import errors move to first use

A typo or a missing dependency no longer fails at startup. It fails when that code path first runs, which might be a rarely used command or the first request in production:

lazy from json import dumsp

print("started fine")
dumsp({"a": 1})
started fine
Traceback (most recent call last):
  File "a08_deferred_error.py", line 1, in <module>
    lazy from json import dumsp
ImportError: lazy import of 'json.dumsp' raised an exception during resolution
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "a08_deferred_error.py", line 4, in <module>
    dumsp({"a": 1})
    ^^^^^
ImportError: cannot import name 'dumsp' from 'json' (.../json/__init__.py). Did you mean: 'dump'?

The traceback shows both the import line and the line that triggered it, which helps. But the program printed started fine first. Add a CI step that imports every module eagerly, such as running the test suite in default mode or a smoke test that calls each command, so broken imports are still caught before deploy.

globals() and __dict__ return proxies

Reading the name normally reifies it, but globals(), a module's __dict__ and dir() do not. In our test, globals()['json'] was a lazy_import object until the code used json, and then it was a module. Code that walks a module's namespace, such as plugin discovery, some serializers or debug tooling, may see proxies. Call .resolve() on a proxy or check for types.LazyImportType.

Import order and timing change

Modules load in the order your code uses them, not in the order of the import lines. Code that configures logging, patches a library or sets environment variables at import time may now run later, or in a different thread. PEP 810 says reification follows the normal import lock, so it is thread-safe. But any module whose top-level code depends on running early will need to stay eager.

Mistakes to avoid

  • Marking imports lazy and then using them at module level. Base classes, decorators and module-level constants reify the import straight away. Check sys.modules after startup.
  • Turning on -X lazy_imports=all in production without a filter. It changes third-party code too, and import-for-side-effect modules stop running.
  • Losing import errors in CI. If tests don't exercise a code path, its broken import only appears in production.
  • Expecting faster requests. Lazy imports help processes that start often and use a fraction of their dependencies. A warm web worker serving requests gains nothing per request.
  • Relying on the PEP's none mode. It wasn't accepted by the 3.15.2 build we tested. Use a filter.
  • Using the keyword in code that still has to run on 3.14. Use __lazy_modules__ until you drop older versions.

A rollout plan

  1. Measure the startup time of the commands and functions that run most often, and list the slowest imports with -X importtime.
  2. Mark the two or three heaviest imports in those entry points as lazy, using the keyword on 3.15-only code and __lazy_modules__ elsewhere.
  3. Check sys.modules after startup to confirm they really stayed unloaded, and move module-level uses into functions or separate modules.
  4. Keep side-effect imports eager, and keep at least one eager test run in CI.
  5. Try -X lazy_imports=all with a filter on CLIs and batch jobs only after the test suite passes under it. For web servers, measure first-request latency and worker memory before enabling it.

If your background workers are where startup time hurts, see our Celery and Redis guide for Django.

What we tested and what we didn't

Everything here ran on 4 December 2026 on one Linux machine, using CPython 3.15.2 and 3.14.10 builds installed with uv. We ran each code block in this article and compared its output to what we describe (14 of 14 checks passed). Timings are medians of 30 runs for the CLI and 20 for Django. They include process start and depend on disk cache and CPU, so treat them as relative numbers. We did not test large Django projects, Gunicorn or uWSGI with --preload, memory sharing between forked workers, Celery workers, AWS Lambda or other serverless runtimes, the free-threaded 3.15 build, or type checkers and IDEs handling the new syntax.

FAQ

Which Python version supports lazy imports?

The lazy keyword, __lazy_modules__ and -X lazy_imports are new in Python 3.15. On older versions the keyword is a syntax error, and __lazy_modules__ is ignored.

Are lazy imports the same as importing inside a function?

The effect on startup is similar, but the import stays at the top of the file where readers and tools expect it. Imports written inside functions are always eager and run each time the function is called (after the first call, they are a cheap sys.modules lookup).

Do lazy imports slow down my code after startup?

Once a name is used, it refers to the real module. PEP 810 states that the lazy check is optimised away after a few accesses. We didn't benchmark steady-state code, only startup.

Is it safe to use -X lazy_imports=all with Django?

Our small Django 6.1 project passed its checks, migrations and tests under it. That doesn't prove much about a large project with third-party apps that register things at import time. Test your own project, and start with a filter.

Conclusion

Python lazy imports let you keep imports at the top of the file and still not pay for libraries a run doesn't need. In our tests that took a CLI command from 288 ms to 22 ms and cut Django management commands by about a third, with no source changes for Django. The work is in the details: module-level code that uses a lazy name, side-effect imports that stop running, and errors that appear later than before. Start with your slowest entry points, measure, and be careful with the global switch.

If your Python CLIs, Django services or background jobs are slow to start, or you're planning a move to Python 3.15, CodeSapient can help with profiling, the upgrade and the rollout. See our development services or contact us.

← Back to Blog