• Python
  • performance
  • Python 3.15
  • imports

Python 3.15 lazy imports: a step-by-step guide to faster startup, with measured results

A beginner's guide to the lazy import keyword added in Python 3.15 (PEP 810): what it does, how to measure import cost with -X importtime, a tested CLI example that went from about 90 ms to about 28 ms, the places lazy is not allowed, and the mistakes that change program behavior.

Imagine you wrote a small command-line tool (a CLI, short for command-line interface) in Python. Typing tool version should print one line and exit, yet it takes a noticeable moment, because the first lines of the file import asyncio, http.client, sqlite3 and a few other modules. That one command never uses any of them. Python still loads every one before it runs your first real line.

Python 3.15, released on 9 October 2026, adds a direct fix for this: the lazy keyword. You keep your imports at the top of the file, but a module is only loaded when your code first uses it. What’s new in Python 3.15

This guide explains how lazy imports work, shows how to find out which imports are slow, walks through a converted CLI with measured numbers, and lists the cases where a lazy import changes what your program does. Every example below was run on CPython 3.15.0 (installed with uv python install 3.15.0) on Linux. uv puts python3.15 in ~/.local/bin; if your shell cannot find it, use the full path printed by uv python find 3.15.0.

What “importing a module” actually costs

A module is a Python file (or a compiled extension) that you load with import. When Python runs import json, it does several things right away: it searches the folders on sys.path for the module, reads the file, compiles it to bytecode (the internal instructions Python executes) if no cached copy exists, and then runs all of the module’s top-level code. That top-level code usually imports more modules, so one line can pull in dozens of files. What’s new in Python 3.15

Until now, the usual workaround was to move the import inside the function that needs it. That works, but imports end up scattered through the code and you lose the quick overview at the top of the file.

Three terms are used throughout this article:

  • Eager import: the normal behavior. The module is loaded when the import line runs.
  • Lazy import: the module is not loaded at the import line. Python binds the name to a placeholder and loads the module on first use.
  • Proxy: that placeholder object. Its type is available as types.LazyImportType.

How the lazy keyword works

lazy is a soft keyword: it only has a special meaning directly before import or from. Elsewhere it is an ordinary name, so old code with a variable called lazy keeps working (we checked: lazy = 3; print(lazy) prints 3 on 3.15.0). The feature was specified in PEP 810, accepted on 3 November 2025.

Both import forms are supported:

lazy import json
lazy from pathlib import Path

When code first reads the name json, Python finds and runs the module, then replaces the proxy with the real module object. With lazy from pathlib import Path, the whole pathlib module is loaded on first use of Path, not just that one name. Python reference: lazy imports

Step 1: see the delay disappear

To make the effect obvious, create a deliberately slow module. Save this as slowmod.py:

import time
print("slowmod: loading (side effect)")
time.sleep(0.5)

def hello():
    return "hi from slowmod"

Then save this as app_lazy.py in the same folder:

import sys, time, types
t = time.perf_counter()
lazy import slowmod
print(f"startup {time.perf_counter() - t:.3f}s")
print("in sys.modules?", "slowmod" in sys.modules)
print("proxy?", isinstance(globals()["slowmod"], types.LazyImportType))
print(slowmod.hello())
print("in sys.modules?", "slowmod" in sys.modules)
print("proxy after use?", isinstance(globals()["slowmod"], types.LazyImportType))

Run it from a terminal in that folder with python3.15 app_lazy.py. On our machine the output was:

startup 0.000s
in sys.modules? False
proxy? True
slowmod: loading (side effect)
hi from slowmod
in sys.modules? True
proxy after use? False

Read it line by line. The import line took no measurable time. slowmod was not in sys.modules, the dictionary of modules Python has loaded. Reading globals()["slowmod"] returned the proxy, because direct dictionary access does not trigger loading. The call slowmod.hello() loaded the module, which is when its print ran and the half-second sleep happened. Afterwards the name pointed to the real module. The same file with a plain import slowmod reports startup 0.501s.

Measure before you change anything

Lazy imports only help if imports are actually what makes startup slow. Python has had a built-in way to check this since 3.7: the -X importtime option prints one line per imported module to standard error (stderr).

Step 2: find the expensive imports

Here is a small CLI, saved as tool_eager.py:

import argparse
import asyncio
import http.client
import json
import sqlite3
import tomllib
from email.message import EmailMessage

def main():
    p = argparse.ArgumentParser(prog="tool")
    p.add_argument("command", choices=["version", "fetch"])
    args = p.parse_args()
    if args.command == "version":
        print("tool 1.0")
    else:
        conn = http.client.HTTPSConnection("example.com")
        print(type(conn).__name__, json.dumps({"ok": True}))

main()

Run this to list the slowest imports. 2>&1 >/dev/null sends the timing lines into the pipe (|, which passes one command’s output to the next command) and throws away the program’s own output; sort orders them by the cumulative column:

python3.15 -X importtime tool_eager.py version 2>&1 >/dev/null | sort -t'|' -k2 -n | tail -4

Each line shows “self” microseconds (that module alone) and “cumulative” microseconds (that module plus everything it imported). Our top results were:

import time:       654 |      16221 |       concurrent.futures._base
import time:       216 |      16641 |     concurrent.futures
import time:      1298 |      44470 |   asyncio.base_events
import time:       569 |      56858 | asyncio

So asyncio alone took about 57 ms of import time, for a command that never uses it. To count them, run python3.15 -X importtime tool_eager.py version 2>&1 >/dev/null | grep -c 'import time:'. It printed 197; one of those lines is the column header, so 196 modules were imported to print tool 1.0.

Step 3: mark the unused-at-startup imports lazy

Copy the file to tool_lazy.py and add lazy to every import that the version path does not need. Keep argparse eager, because main() uses it on every run:

import argparse
lazy import asyncio
lazy import http.client
lazy import json
lazy import sqlite3
lazy import tomllib
lazy from email.message import EmailMessage

The rest of the file stays the same. python3.15 tool_lazy.py fetch still prints HTTPSConnection {"ok": true}, so the fetch path works: http.client and json are loaded when that branch first touches them.

Step 4: compare the numbers

With the lazy version, the same count printed 63, so 62 modules instead of 196. To time the whole process, we ran each script 30 times and took the median (the middle value, which is barely affected by a few slow runs):

import subprocess, sys, time, statistics
py = sys.argv[1]
for f in ["tool_eager.py", "tool_lazy.py"]:
    ts = []
    for _ in range(30):
        t = time.perf_counter()
        subprocess.run([py, f, "version"], stdout=subprocess.DEVNULL, check=True)
        ts.append(time.perf_counter() - t)
    print(f"{f}: median {statistics.median(ts)*1000:.0f} ms")

Run it as python3 bench.py "$(uv python find 3.15.0)" (any Python can run the timer; the argument is the interpreter being measured). Two runs gave:

tool_eager.py: median 90 ms
tool_lazy.py: median 27 ms
tool_eager.py: median 88 ms
tool_lazy.py: median 28 ms

For comparison, starting Python with nothing to do (python3.15 -c pass) took a median of 12 ms on the same 4-core Linux container. Your numbers will differ with hardware and disk cache, so measure on your own machine. The pattern is what matters: lazy imports remove the cost of modules a given run never touches, and change nothing for modules it does use.

Where lazy is not allowed

The rules are strict, and Python reports a violation as a SyntaxError before running anything. These are the exact messages from 3.15.0:

Code Result
lazy import json inside a def SyntaxError: lazy import not allowed inside functions
lazy import json inside try: SyntaxError: lazy import not allowed inside try/except blocks
lazy from os import * SyntaxError: lazy from ... import * is not allowed

The reference documentation also forbids lazy in a class body and with from __future__ import .... Python reference: lazy imports

Errors move to the first use

With an eager import, a missing module fails at the import line. With a lazy import it fails where the name is first used. Save this as app_missing.py:

lazy import does_not_exist
print("import line passed")
does_not_exist.run()

Running it prints import line passed, then a traceback that names both places (shortened here):

  File ".../app_missing.py", line 1, in <module>
    lazy import does_not_exist
ImportError: lazy import of 'does_not_exist' raised an exception during resolution

The above exception was the direct cause of the following exception:

  File ".../app_missing.py", line 3, in <module>
    does_not_exist.run()
ModuleNotFoundError: No module named 'does_not_exist'

This is useful for debugging, but it means a typo in a rarely used import can stay hidden until that code path runs. Test every command of your tool, not only the common one.

Common mistakes

1. Relying on an import’s side effects. A side effect is something a module does when it loads, beyond defining names, such as registering a plugin. A lazy import delays that. In our test, plugin_a.py appends "a" to a shared REGISTRY list when loaded. With lazy import plugin_a, the program printed registered plugins: [], because nothing ever used the name plugin_a.

# plugin_reg.py
REGISTRY = []

# plugin_a.py
import plugin_reg
plugin_reg.REGISTRY.append("a")

# side.py (run this one)
lazy import plugin_a
import plugin_reg
print("registered plugins:", plugin_reg.REGISTRY)

PEP 810 warns that side effects are deferred until first use and recommends explicit initialization functions instead of import-time registration. PEP 810 FAQ If you cannot change that code yet, keep such imports eager.

2. Wrapping a lazy import in try/except ImportError. The common “optional dependency” pattern (try: import ujson as json / except ImportError: import json) cannot be lazy: the lazy keyword there is a syntax error, and PEP 810 says imports inside try stay eager even in the global “all” mode described below, which we confirmed on 3.15.0. PEP 810: global lazy imports control Leave these imports as they are.

3. Expecting sys.path changes to apply at the import line. The module search happens when the name is first used, so changing sys.path or import hooks (custom code that tells Python how to find or load modules) in between can change which file gets loaded. PEP 810: reification

4. Using lazy in code that must run on Python 3.14 or older. Older interpreters see lazy import x as invalid syntax. We confirmed that Python 3.11 rejects tool_lazy.py with SyntaxError: invalid syntax. The next section shows the compatible alternative.

Supporting older Python versions with __lazy_modules__

A module can list the names that should be lazy in a variable called __lazy_modules__. On 3.15, regular module-scope import statements for those names become lazy, with the same rules as the keyword. On older versions, the variable is just an unused list and the imports run eagerly. Python reference: compatibility via __lazy_modules__

Save this as compat.py next to slowmod.py from Step 1:

__lazy_modules__ = ["slowmod"]
import sys
import slowmod
print(sys.version.split()[0], "loaded at import line?", "slowmod" in sys.modules)
print(slowmod.hello())

On 3.15.0 this printed 3.15.0 loaded at import line? False before the module’s own message. On 3.11.18 the module’s message came first, followed by 3.11.18 loaded at import line? True. The names must be fully qualified (for example "mypackage.sub.utils", not ".sub.utils").

Global controls, and why to use them carefully

You can also change the default for a whole program without editing files:

  • python3.15 -X lazy_imports=all app.py, or the environment variable PYTHON_LAZY_IMPORTS=all, makes every eligible module-scope import lazy. The default value is normal, which only honors lazy and __lazy_modules__. Command line and environment
  • sys.get_lazy_imports() returns the current mode (normal by default; all with the option above, as we checked). sys.set_lazy_imports("all") changes it for import statements that run afterwards; its documentation says library developers should generally not call it. sys.set_lazy_imports
  • sys.set_lazy_imports_filter(func) installs a function that is called with the importing module name, the imported module name, and the from-list (the tuple of names after import in a from ... import statement, or None). Returning False forces an eager import. A filter can only make imports eager; it cannot make an eager import lazy. sys.set_lazy_imports_filter

Be careful with the “all” mode: it also changes third-party libraries that may depend on side effects. A filter is a safer start. In our test, a filter that returned imported.startswith("myapp") under “all” mode kept myapp.slow_module unloaded while json loaded eagerly. The filter was also called for every internal import that json itself made (json.decoder, re, enum, and about fifty more), so keep filter functions fast and free of slow work. When something looks wrong, sys.lazy_modules is a set of names that were lazily imported but not yet loaded, meant for debugging; the docs note it may contain extra entries, so treat it as a hint. sys.lazy_modules

How to verify a conversion

Before you ship a change like this, check four things:

  1. Measure both versions with -X importtime and a repeated timing loop, on the commands users run most.
  2. Run every command and test, so each lazy name is used at least once and any broken import fails in CI (continuous integration, your automated test run) rather than for a user.
  3. Search for side-effect imports, such as plugin registration, logging configuration or import x # noqa lines that exist only to run code, and keep them eager.
  4. Check your minimum Python version. If you support anything older than 3.15, use __lazy_modules__ instead of the keyword.

Conclusion

Lazy imports in Python 3.15 move the cost of loading a module from the import line to the first time the module is used. For programs with several entry points, such as CLIs, test runners and web apps with rarely used features, that can remove most of the startup time: in our test a version command went from about 90 ms to about 28 ms by adding six lazy keywords. Measure first with -X importtime, mark only the imports a common path does not need, keep side-effect imports eager, and use __lazy_modules__ if your code must still run on older versions.

If you are also deciding which runtime versions to support across a project, the same “test before you switch” approach appears in our guide to choosing a Node.js LTS line.

Written by Duy Pham Independent developer. I build the apps on this site and write about how they work.

More about me