Languages

How to Use Python 3.15 Lazy Imports to Cut Startup Time (2026)

The new lazy keyword defers imports until first use. Here is how to measure, convert and roll it out without breaking production.

Paige Donnelly

Senior Backend Engineer

Published 7 min read
Lines of source code displayed on a screen
On this page 6 sections

Python 3.15 lazy imports defer a module's load until its first use. To adopt them, profile startup with -X importtime, mark heavy top-level imports as lazy, keep modules with import-time side effects eager, and test that failures now surface at first use. PEP 810 reports startup savings of 50 to 70 percent for short-lived command-line programs.

Backtrace tests developer tools against real codebases, and Python's new import behavior is one of the few language changes that can shave real time off a production deploy. Python 3.15 shipped on October 9, 2026, so teams are now deciding whether to adopt it. This guide is for backend engineers who own a CLI, a worker or a serverless function written in Python.

It covers what the keyword does, how to find the imports worth changing, how to roll the change out, and what breaks when startup code stops running at startup.

What Does the lazy Keyword Do in Python 3.15?

The lazy soft keyword marks an import as deferred. Python binds the name to a lightweight proxy object and loads the real module only when your code first touches that name. Until then, no file is read, compiled or executed. The import statement stays at the top of the file where readers expect it.

The What's New in Python 3.15 documentation shows the syntax. It works for both import and from-import forms:

text
lazy import json
lazy from pathlib import Path

print("Starting up...")  # neither module is fully imported yet

data = json.loads('{"key": "value"}')  # json loads here
p = Path(".")                          # pathlib loads here

The rules are strict. Lazy imports are allowed only at module scope. Using lazy inside a function, a class body or a try, except or finally block raises a SyntaxError. Star imports and future imports cannot be lazy either.

Failures behave differently, too. If a lazily imported module does not exist, Python raises the error where the name is first used, not at startup. The traceback includes both the access site and the original import line, so the cause is easy to trace.

How Do You Find Which Imports Are Worth Making Lazy?

A stopwatch on a desk, standing in for measuring Python startup time

Profile startup with the -X importtime flag, which prints how long each module takes to import. Sort the output by cumulative time and look at the top entries. Any heavy module that your program rarely uses on its main path is a candidate for a lazy import.

Run the measurement against the command people actually use, not an empty script. A CLI's help screen and its most common subcommand are the usual starting points. Work through these steps:

  1. Run python -X importtime -m yourapp.cli --help 2> imports.log.
  2. Sort the log by the cumulative column and read the top 20 lines.
  3. Note which heavy modules your entry point never touches on that path.
  4. Record total wall-clock startup time as your baseline.
  5. Repeat for the two or three commands users run most.

Do not trust a single run. File caches and CPU frequency change the numbers, so repeat each measurement several times and compare medians.

The payoff depends on the program. The PEP 810 specification says lazy imports can cut startup time by 50 to 70 percent in practice for short-lived command-line programs. It also says memory savings of 30 to 40 percent have been observed in real workloads.

Treat those as the proposal's own claims, not a promise for your codebase. A service that uses every dependency on its first request will gain much less.

The same PEP offers a useful clue about demand. Its analysis of the standard library found that about 17 percent of imports outside tests, roughly 3,500 across 730 files, already sit inside functions to defer their cost. Engineers have been hand-rolling this trick for years, and the keyword makes it tidy.

Convert Imports Safely, One Module at a Time

A computer monitor showing code on a developer's workstation

Start with the single heaviest import from your profile and mark it lazy. Run the test suite, check the startup time, then move to the next one. Python 3.15 gives you four ways to control this, and picking the narrowest one keeps the blast radius small.

Convert Imports Safely, One Module at a Time
MechanismScopeBest use
lazy keywordOne import statementTargeted changes in your own code
__lazy_modules__ listNamed modules in one fileCode that must still run on older Python
-X lazy_imports or PYTHON_LAZY_IMPORTSWhole processExperiments and test runs
sys.set_lazy_imports_filter()Chosen modules by callbackMaking only your own packages lazy

The __lazy_modules__ option matters for libraries. If you still support Python 3.14 or earlier, the new keyword is a syntax error on those versions. A module-level list of fully qualified names makes ordinary import statements lazy on 3.15 and leaves them untouched elsewhere.

The command-line flag and the environment variable accept two values. The value all makes every import lazy by default, and normal respects only the keyword. Use all in a branch to find breakage fast, then fall back to explicit markers for production.

Backtrace's editors would add one rule: never ship the global all setting to production without a smoke test behind it.

The filter callback receives the importing module, the imported module and the from-list. Returning True allows the import to be lazy. A filter such as one that matches your own package prefix keeps third-party dependencies eager while your internal modules defer.

Go gradually. The pain here resembles the one in our look at whether TypeScript's strict mode is worth the migration, where flipping everything on at once is the usual mistake.

What Breaks When Imports Stop Running at Startup?

A bundle of tangled cables, a picture of hidden dependencies between modules

Three things break: side effects that never run, circular imports that still fail, and errors that appear late. Each one traces back to the same cause. A lazy import does nothing until something uses the name, so anything that depended on the import happening early now needs another trigger.

Side effects come first. PEP 810 warns that eliding an import also elides its side effects. Plugin registries, decorator-based route tables, signal handlers and model registration are the usual victims. In our experience, the bug is never in the import line itself. It shows up later as a missing route or an unregistered handler.

The PEP's advice is to replace import-time side effects with explicit initialization functions. Call them from your startup code instead of relying on import order.

Circular imports come second. According to the PEP's FAQ, lazy imports do not automatically solve them. They help only if neither module touches the other while it is initializing. If module A reads a value from module B at the top level, you still get an error.

Late errors come third. A typo in a module name or a missing optional dependency used to crash the process at boot. Now it crashes on the first request that needs it. That is a real change for deploys, because a health check can pass while a rarely used code path is broken.

Close that gap with a smoke test. Touch every lazily imported name once in CI so a bad import fails the build, not a customer.

Do Lazy Imports Help Long-Running Services?

A person working at a computer in an office, reviewing a service rollout

They help most at startup and in memory, and they cost almost nothing afterward. The PEP says that once a lazy import has loaded, the interpreter specializes the bytecode and the lazy check disappears. Hot paths run as fast as normal imports. The first caller pays the loading cost once.

That first-call cost is the tradeoff to plan for. A web worker that defers a heavy library moves a delay from boot to the first user who needs it. For serverless functions, where cold starts are the pain, that is often a win. We covered the same pay-now-or-pay-later bargain in why JVM startup time still hurts in serverless.

Warm the important names deliberately. Add a startup hook that touches the two or three dependencies every request needs, so no user ever sees the import delay. Leave the rarely used ones lazy.

A readiness probe is a natural place for this. It runs once per instance before traffic arrives, so the cost lands where it hurts nobody.

The PEP also reports its own overhead test. Against a baseline of 161.2 milliseconds for eager imports, the lazy machinery added between 0.1 and 0.5 percent, which sat inside the noise of the measurement. Switching the feature on does not slow down code that never uses it.

Plan the rollout the way you would plan any runtime change. Pin the Python version in your build image, run the full suite on 3.15, and compare startup time before and after. Our checklist for upgrading to Node.js 26 LTS follows the same pattern for a different runtime.

Conclusion

Lazy imports are a small keyword with a measurable effect. Measure first, change the heaviest imports one at a time, and keep anything with side effects eager until you have given it an explicit initializer.

Then add the smoke test that touches every lazy name. That one check turns the biggest new risk, late import errors, into a failed build. Start with a single CLI or worker this sprint, record the before and after numbers, and expand only where the numbers justify it.

What is the lazy keyword in Python 3.15?
The lazy keyword marks an import so Python defers loading the module until the name is first used. Until then the name is a lightweight proxy. It works with both import and from-import statements, and only at module scope, so it cannot appear inside functions, classes or try blocks.
Can I use lazy imports on older Python versions?
The keyword itself is a syntax error before Python 3.15. To support older versions, define a module-level __lazy_modules__ list of fully qualified module names. On 3.15 and later, regular import statements for those names become lazy, while older interpreters simply import them normally with no change in behavior.
Do lazy imports fix circular import errors?
Not automatically. A lazy import helps only when neither module touches the other during initialization, such as when access happens inside a function called later. If one module reads a value from the other at the top level, you still get an error, so refactor shared code into a third module.
How do I find which Python imports slow down startup?
Run your entry point with the -X importtime flag and send stderr to a file. The output lists self and cumulative time for each module. Sort by cumulative time, focus on heavy modules your common path never uses, and repeat the measurement several times because caches change single-run results.

Written by

Paige Donnelly

Senior Backend Engineer

8+ years experience

Paige Donnelly is a senior backend engineer who has spent the last eight years working on distributed systems, first at a mid-size fintech and then leading a payments infrastructure team through a migration from a monolith to event-driven services. She's on the losing end of more 3am pages than she'd like to admit, which is why she writes about observability, deployment safety, and API design with an eye toward what actually breaks in production rather than what looks good in a conference talk. She contributes to a couple of open-source CLI tools in her spare time and still refuses to use a debugger for anything she can solve with well-placed logs.

Credentials

  • 8 years in backend and distributed systems engineering
  • Former tech lead, payments infrastructure at a Series D fintech
  • Contributor to several open-source developer tooling projects