Deep Engineering
Advanced·Published·3.14 · 3.15·50 MIN

Lazy imports: the module loads on first use, not at startup

Python 3.15 adds lazy import (PEP 810). A command-line tool with sixteen imports answered --help in 48.2 ms instead of 97.0 ms in our measurement. The price: an import error surfaces at the first use, and a module imported for its side effect does not run at all.

Full technical treatment

TL;DR

  • The 3.15 contract: lazy import json binds the name json to a placeholder of type lazy_import, and the module itself is loaded on the first use of the name. Until then the module is not in sys.modules. On 3.14 such a file does not compile, and 3.14.10 silently accepts the -X lazy_imports=all option and changes nothing.
  • Measured on CPython 3.15.2 (2 cores, median of 61 starts): a command-line tool with sixteen imports answered --help in 48.2 ms instead of 97.0 ms and loaded 104 modules instead of 224. The empty interpreter takes 11.0 ms: lazy imports do not go below that floor.
  • A separate measurement for the opposite case (bench/lazy-imports/firstuse.py, 41 runs per variant, a different machine): when the process runs all eight subcommands, the lazy keyword saves nothing noticeable — 113.0 ms versus 114.3 ms, with a measurement resolution of 7.9 ms. The time moves from the import into the first calls: the first call of the subcommand that uses asyncio took 13.83 ms instead of 0.39 ms.
  • -X lazy_imports=all makes module-level imports lazy across the whole program, other people's libraries included (except imports inside try/except and import *): 41.3 ms and 68 modules on --help. The none value that PEP 810 describes does not exist in 3.15.2 — the interpreter refuses to start with it.
  • An import error moves from startup to the first use: the program gets going, and ModuleNotFoundError is raised from the function that touched the name. A failed load does not replace the placeholder, so the next use tries again. So load mandatory dependencies explicitly, before the service reports ready.
  • A module imported for its side effect — registering a plugin, patching a function — does not run at all under a lazy import until someone touches its name. Under all this applies to every such import in the project.
  • __lazy_modules__ does the same without new syntax, so it suits code that must also run on 3.14: there the variable means nothing, while a file with lazy import does not even compile on 3.14.

Why should I care?

Much of a Python program's startup time goes to imports: find the file, read the bytecode, run the module body — for every module in the dependency tree. A command-line tool pays for the whole tree on every call, even when the call is --help. Before 3.15 the fix was to move imports into functions, and the code read worse for it: a module's dependencies were no longer listed at its top.

3.15 has the lazy keyword for this and a global mode that a single option switches on. The option is tempting: add -X lazy_imports=all and startup gets faster. But a lazy import changes more than timing. It moves an import error to another place in the program, defers module side effects, and makes introspection see placeholders instead of modules. Below: what the 3.15.2 documentation promises, what the 3.15.2 interpreter did in our experiments, and what it saved on a concrete tool. The measurements ran on a two-core machine.

What was checked where

The evidence here comes from three levels, and they do not always agree. PEP 810 is the design of the mechanism. The documentation at tag v3.15.2 is the release's contract. The run records show the behaviour of three specific builds from python-build-standalone: CPython 3.14.10, 3.15.2 and 3.15.2t (free-threaded, used only in the threads experiment). Where the PEP and the release disagree (the none value, covered below), the article follows the release. Below are five ways to switch laziness on, each tested in its own fresh interpreter:

bench/lazy-imports/versions.py, records versions-3.14.10.txt and versions-3.15.2.txt: what the import of json became.

way3.14.103.15.2
lazy import jsonSyntaxError, the file does not compilea lazy_import placeholder
__lazy_modules__ = ['json']a plain importa lazy_import placeholder
-X lazy_imports=allaccepted silently, kept in sys._xoptions, the import is plaina lazy_import placeholder
PYTHON_LAZY_IMPORTS=allno effecta lazy_import placeholder
sys.set_lazy_imports("all")AttributeErrora lazy_import placeholder

The third row is a trap when moving between versions. Python does not reject an -X option with an unknown name, so a launch command with -X lazy_imports=all looks the same on both versions and simply does nothing on 3.14.10. Every command with -X or the environment variable in this article was checked on 3.15.2.

The global mode also changes the behaviour of code you did not write: in the measurements below it silently switches off plugin registration, function patching and class auto-discovery. It is not a free startup optimisation; the section "When to switch it on" lists what to check before you enable it.

Mental model: the name exists, the module does not yet

A plain import json does two things at once: loads the module and binds the name. lazy import json does only the second — and binds the name not to the module but to a placeholder.

language contractLanguage reference, section Lazy imports, tag v3.15.2

the module is not loaded immediately at the import statement. Instead, a lazy proxy object is created and bound to the name. The actual module is loaded on first use of that name.

Three fields of state show what this looks like from the inside:

2. SYS.MODULES BEFORE AND AFTER THE FIRST USE
---------------------------------------------
after the statement    'json' in sys.modules: False 'json' in sys.lazy_modules: True  globals()['json'] is lazy_import
repr before first use: <lazy_import 'json'>
after json.dumps()     'json' in sys.modules: True  'json' in sys.lazy_modules: False globals()['json'] is module

After the statement the module's globals hold an object <lazy_import 'json'>, json is not in sys.modules, but it is in the new set sys.lazy_modules. The first use of the name — here json.dumps — loads the module with an ordinary import and replaces the placeholder in the module's dictionary with the real module. From then on the name is indistinguishable from a plainly imported one. PEP 810 calls this step reification.

What matters here is what happens between the steps. What counts as "using the name" is the interpreter's call: reading the name or a module attribute triggers loading; reading the module's dictionary directly does not. Hence the second and third scenarios in the figure: globals()["json"].resolve() loads the module, but the dictionary keeps the placeholder; only an ordinary access by name replaces it. And a failed load replaces nothing, so every later use looks for the module again.

The whole sequence has four stages:

  1. lazy import json runs: nobody looks for the module.
  2. A placeholder in the global name: the module's dictionary holds a lazy_import under the key json, and the name is recorded in sys.lazy_modules.
  3. The first read of the name — json.dumps(...) in the module's code or mod.json from outside.
  4. Loading and rebinding: an ordinary import runs, and the placeholder in the module's dictionary is replaced with the module.

A special case is reading the module's dictionary directly (globals(), vars(mod), mod.__dict__): it stops at the second stage and hands back the placeholder.

implementation detail · 3.15.2Python/bytecodes.c, Python/ceval.c, Objects/moduleobject.c, Objects/lazyimportobject.c

How CPython 3.15.2 implements the stages. Stage 1: the lazy flag is stored in the argument of the IMPORT_NAME instruction. Stage 3: reads of a global name (LOAD_GLOBAL, LOAD_NAME) and module attribute access check for the placeholder. Stage 4: _PyLazyImport_Reify calls __import__, and the replacement in the module's dictionary is conditional — _PyDict_ReplaceItemIf stores the value only if the same placeholder is still there. This is an implementation detail, not a promise of the language.

Where lazy is allowed

lazy is a soft keyword: it means something only right before import or from, and a variable called lazy stays legal. Each place was checked in a fresh interpreter:

1. WHERE THE LAZY KEYWORD IS ALLOWED
------------------------------------
module level                 ok
inside if at module level    ok
inside with at module level  ok
inside a function            SyntaxError: lazy import not allowed inside functions
inside a class body          SyntaxError: lazy import not allowed inside classes
inside try/except            SyntaxError: lazy import not allowed inside try/except blocks
lazy from m import *         SyntaxError: lazy from ... import * is not allowed
lazy from __future__         SyntaxError: lazy from __future__ import is not allowed
name 'lazy' as a variable    ok

The ban inside functions makes sense: an import in a function already runs only when the function is called. The ban inside try/except matters more than it looks. The familiar "try to import, fall back if missing" pattern makes no sense without an immediate import: the exception would be raised not inside try, but later, somewhere in code not ready for it. So such an import has to stay plain.

On 3.14.10 each of the eight lines with lazy fails with SyntaxError: invalid syntax. That is a compile error, so on 3.14 the whole file fails to import, not one line. Code that must run on both versions cannot use the keyword; for it there is __lazy_modules__, covered below.

lazy from: one name at a time

With lazy from decimal import Decimal, localcontext each name becomes a placeholder. The first use of one of them loads the whole module but replaces only that name:

3. LAZY FROM: EACH NAME IS RESOLVED SEPARATELY
----------------------------------------------
after the statement      decimal loaded: False Decimal is lazy_import localcontext is lazy_import
after Decimal('1.5')     decimal loaded: True  Decimal is type        localcontext is lazy_import
after localcontext()     decimal loaded: True  Decimal is type        localcontext is builtin_function_or_method

decimal is already loaded while localcontext is still a placeholder — until its own first use. There is no second import: the module is already in sys.modules.

What it buys at startup

The measurement uses a command-line tool of the kind almost every project has: eight subcommands, each with its own dependencies, all sixteen imports at the top of the file — argparse, asyncio, csv, decimal, email.message, http.client, io, json, logging, sqlite3, subprocess, urllib.request, xml.etree.ElementTree, zipfile, dataclass and Path. Two commands are called: --help, which needs nothing but argparse, and report, which needs json, csv and decimal.

Three files — bench/lazy-imports/cli_eager.py, bench/lazy-imports/cli_lazy.py and bench/lazy-imports/cli_compat.py — differ only in the import block, and the measuring script checks that before it starts. Every start is a separate process with -I, 61 rounds, all configurations in shuffled order in each round.

bench/lazy-imports/startup.py, blocks 1 and 3: median process time and the number of modules in the -X importtime list.

Pythonvariant--help, msmodulesreport, msmodules
3.14.10empty interpreter11.125——
3.14.10plain imports91.322091.4220
3.14.10__lazy_modules__93.322091.9220
3.15.2empty interpreter11.025——
3.15.2plain imports97.022488.0223
3.15.2lazy keyword48.210441.1113
3.15.2__lazy_modules__48.010440.5113
3.15.2-X lazy_imports=all41.36833.476

What matters is the 3.15.2 rows. The keyword cuts 48.8 ms off --help out of the 86.0 ms that lie above the empty interpreter (97.0 − 11.0; computed from the unrounded medians, block 4 of the record gives 85.9) — more than half; for report it is 61% of the same portion. "Twice as fast" is an observation about this tool on this machine, not a property of lazy imports: the gain equals the cost of the modules this call did not touch.

measured observationbench/lazy-imports/startup.py, runs/startup.txt, CPython 3.14.10 and 3.15.2, 2 vCPU Intel Xeon 2.30GHz

The medians of odd and even rounds of one configuration differ by 0.1 to 4.1 ms — this measurement does not resolve differences below 4 ms. The interquartile range is 6 and 11 ms for plain imports on 3.15.2 (--help and report) and 2 to 8 ms for the lazy variants. The machine's one-minute load average was 0.2 before the measurement and 0.7 after, and it is printed in the record. The child's CPU time (block 2 of the record) almost equals the wall time: the process did not wait for a core.

The last column of block 3 shows why it is 104 modules rather than a couple of dozen:

3.15.2   lazy keyword          --help       104    yes  5 of 16: argparse, io, logging, dataclasses, pathlib

argparse is genuinely needed for --help. logging and dataclasses are loaded while the tool itself loads: the line log = logging.getLogger("tool") and the @dataclass decorator on the config class touch those names at module level. A lazy import defers loading until the first use, not forever, and a use at module level is still a use. The tool does not touch io and pathlib itself: logging loads them with its own plain imports. This is the usual picture: the gain is eaten up by the names a module touches while it loads.

Two more rows of the table need a caveat.

  • -X lazy_imports=all beats the keyword — 41.3 ms against 48.2 ms, a difference above the resolution of the measurement — because it also makes imports inside the standard library lazy: 68 modules instead of 104, and pathlib, which came in through logging in the keyword variant, is no longer loaded. That is both the gain and the risk: the mode reaches code you did not write.
  • 3.14.10 and 3.15.2 with plain imports are not compared here. The 3.15.2 standard library uses lazy imports itself: site.py lazily imports locale, pkgutil, traceback and warnings, and there is lazy import in argparse, dataclasses, typing, pathlib and two dozen more modules. The difference between the versions with plain imports is a difference between libraries, not syntax. Only variants within one version are worth comparing.

When the work is needed after all

The startup measurement shows the best case for lazy imports: the call needs only a small part of the dependencies. In the opposite case, the process imports the same tool as a module and runs all eight subcommands in a row, and then once more. Inside the process, a clock times the import and the first and second calls of each subcommand; from outside, we time the whole process.

bench/lazy-imports/firstuse.py, block 1: medians of 41 processes per configuration, ms.

variantprocessimportfirst callssecond callsmodules
plain imports114.359.011.16.4232
lazy keyword113.011.555.56.7230
-X lazy_imports=all99.711.753.36.8184

With the keyword the process as a whole did not get faster: 113.0 ms versus 114.3 ms, while the medians of odd and even rounds of one configuration differ here by up to 7.9 ms. The import got 47.5 ms cheaper and the first calls 44.4 ms more expensive — the same work, only in a different place. The second calls cost the same. The global mode saved 14.6 ms, more than the resolution: it did not load 48 modules that the standard library imports but these subcommands never touched.

The per-subcommand breakdown shows where exactly the time went:

2. FIRST AND SECOND CALL OF EACH SUBCOMMAND, MS
-----------------------------------------------
subcommand        plain imports 1st/2nd         lazy keyword 1st/2nd  -X lazy_imports=all 1st/2nd
report                     0.08 /  0.06                 1.32 /  0.06                 2.69 /  0.06
fetch                      7.00 /  5.30                29.71 /  5.59                17.45 /  5.65
mail                       3.37 /  0.56                 3.30 /  0.60                 4.86 /  0.60
db                         0.16 /  0.10                 0.75 /  0.10                 1.60 /  0.10
pack                       0.12 /  0.09                 1.69 /  0.11                 3.10 /  0.10
xml                        0.04 /  0.03                 2.07 /  0.03                 5.01 /  0.03
run                        0.04 /  0.03                 2.33 /  0.03                 2.84 /  0.03
wait                       0.39 /  0.24                13.83 /  0.23                15.74 /  0.23

With lazy imports the first call of wait (it needs asyncio) took 13.83 ms versus 0.39 ms, and the first fetch (urllib.request, http.client) took 29.71 ms versus 7.00 ms. For a server, this means the first request that needs a deferred module pays for loading it. We did not measure a service's tail latency under load: this is one process with no competing requests. The section on threads shows what happens to requests that arrive while the module is loading.

measured observationbench/lazy-imports/firstuse.py, runs/firstuse.txt, CPython 3.15.2, 2 vCPU Intel Xeon 2.10GHz

Here the tool is imported as a module, so its .pyc comes from the cache, and fetch does not touch the network. This record was taken on a machine at 2.10 GHz, the startup.txt record at 2.30 GHz; numbers from the two records are not compared with each other. The one-minute load average was 0.2 before the measurement and 0.3 after.

Global mode, __lazy_modules__ and the filter

In CPython 3.15.2 the global mode is switched on with -X lazy_imports=all, the environment variable PYTHON_LAZY_IMPORTS=all, or the function sys.set_lazy_imports("all"). On 3.14.10 none of the three switches laziness on: the option and the variable are silently ignored, and the function does not exist (see the table at the start of the article). In this mode every module-level import becomes "potentially lazy" — as if lazy stood in front of it.

4. GLOBAL MODE
--------------
default                    mode, sys.flags.lazy_imports: normal -1
-X lazy_imports=all        mode, sys.flags.lazy_imports: all 1
PYTHON_LAZY_IMPORTS=all    mode, sys.flags.lazy_imports: all 1
env all, -X normal         mode, sys.flags.lazy_imports: normal -1
-X lazy_imports=none       exit 1: Fatal Python error: config_init_lazy_imports: -X lazy_imports: invalid value; expected 'all' or 'normal'
PYTHON_LAZY_IMPORTS=none   exit 1: Fatal Python error: config_init_lazy_imports: PYTHON_LAZY_IMPORTS: invalid value; expected 'all' or 'normal'
set_lazy_imports(none)     ValueError: mode must be 'normal' or 'all'

The -X option takes precedence over the environment variable. There are two values, all and normal, exactly as the 3.15.2 documentation says: Both accept two values. PEP 810, whose status is Final, describes a third one: "none" (force all imports to be eager). The 3.15.2 release does not have it: with -X lazy_imports=none the interpreter does not start at all, and sys.set_lazy_imports("none") raises ValueError. If the plan was "switch laziness off entirely in tests", that does not work on 3.15.2; the lazy keyword in the code stays lazy in any mode.

Which plain imports all makes lazy and which it does not:

with -X lazy_imports=all, which plain imports became lazy:
  json     loaded: False global is lazy_import
  Decimal  loaded: False global is lazy_import
  csv      loaded: True  global is module
  zipfile  loaded: True  global is -
(import inside try/except and inside a function stay eager; zipfile is local to f)
implementation detail · 3.15.2Python/codegen.c

The compiler marks an import inside try/except and an import in a function as forced eager — the comment in the source reads "force eager import in try/except block". So try: import yaml except ImportError: yaml = None behaves as before even under all.

__lazy_modules__ is the option for code that must also run on 3.14. It is a module-level variable holding a list of fully qualified module names; a plain import or from … import of such a module becomes lazy, as with the keyword. The same snippet on the two versions:

5. __LAZY_MODULES__ WITHOUT NEW SYNTAX
--------------------------------------
json loaded: False | csv loaded: True | xml.dom.minidom loaded: False
after json.dumps(): json loaded: True

On 3.14.10 the first line reads json loaded: True | csv loaded: True | xml.dom.minidom loaded: True: the variable means nothing there, and the file simply runs as before. In the startup measurement __lazy_modules__ on 3.15.2 matched the keyword: 48.0 ms versus 48.2 ms, which at a resolution of 4.1 ms is the same thing.

The third lever is the filter sys.set_lazy_imports_filter. It is called for each potentially lazy import when the statement runs, not at the first use, with three arguments: who imports, what, and the list of names for from. Return False and the import runs immediately:

6. FILTER DECIDES AT THE IMPORT STATEMENT
-----------------------------------------
plugins.csv_export: module body runs
json loaded: False | plugins.csv_export loaded: True
filter called with ('__main__', 'json', None)
filter called with ('__main__', 'plugins.csv_export', None)

The sys documentation treats the two functions differently. About set_lazy_imports it says outright who should not use it: Library developers should generally not use this function as it affects the runtime execution of applications. About the filter, it says that it is an advanced feature intended for specialized users who need fine-grained control over lazy import behavior.

What breaks

An import error, at the first use

The tool lazily imports a module that is not installed and starts handling a request:

1. IMPORT ERROR MOVES TO THE FIRST USE
--------------------------------------
app started, handling request
attempt 1: ModuleNotFoundError: No module named 'yaml_that_is_not_installed'
           __cause__: ImportError("lazy import of 'yaml_that_is_not_installed' raised an exception during resolution")
attempt 2: ModuleNotFoundError: No module named 'yaml_that_is_not_installed'
           __cause__: ImportError("lazy import of 'yaml_that_is_not_installed' raised an exception during resolution")
global is still lazy_import
--- stderr of the last, uncaught attempt (exit 1) ---
Traceback (most recent call last):
  File "<tmp>/app.py", line 1, in <module>
    lazy import yaml_that_is_not_installed as yaml
ImportError: lazy import of 'yaml_that_is_not_installed' raised an exception during resolution

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

Traceback (most recent call last):
  File "<tmp>/app.py", line 14, in <module>
    load_config("a: 1")
    ~~~~~~~~~~~^^^^^^^^
  File "<tmp>/app.py", line 5, in load_config
    return yaml.safe_load(text)
           ^^^^
ModuleNotFoundError: No module named 'yaml_that_is_not_installed'
--- same file with a plain import: exit 1, stdout '' ---
ModuleNotFoundError: No module named 'yaml_that_is_not_installed'

With a plain import the program dies before its first line of output. With a lazy one it gets to print "app started, handling request", and the exception is raised from load_config — the function that touched the name. The traceback is honest: it has two parts, and the first points at the lazy import line, as What's New promises. But the exception type is the same, ModuleNotFoundError, and any except ImportError or except Exception on the way up from load_config will catch it — a handler written for something else entirely.

Two practical consequences follow. A service with a missing dependency now starts, may pass its readiness check, and then fails on the first request that needs the dependency. And the failure is not cached: the output shows global is still lazy_import, and the second attempt looks for the module again, paying the full cost of the search again.

Mandatory dependencies: load them before readiness

To make the error surface at startup again, load mandatory dependencies explicitly before the service reports ready. The steps:

  1. List the modules the service cannot work without.
  2. At initialisation, load each one — importlib.import_module(name).
  3. Report readiness only after all of them have loaded without errors.
  4. Leave lazy the modules that only rare code paths need.
PYTHON
PYTHON
import importlib
lazy import json
lazy import yaml
 
REQUIRED = ["json", "yaml"]
 
def warm_up():
    for name in REQUIRED:
        importlib.import_module(name)
 
warm_up()          # before reporting ready

The measurement runs the same code, except that instead of yaml it imports a module that does not exist (lazy import yaml_that_is_not_installed as yaml), without the warm-up and with it:

1. REQUIRED IMPORTS FORCED BEFORE THE SERVICE SAYS READY
--------------------------------------------------------
no warm-up           exit 1, stdout: ready  error: ModuleNotFoundError: No module named 'yaml_that_is_not_installed'
warm-up of REQUIRED  exit 1, stdout: -      error: ModuleNotFoundError: No module named 'yaml_that_is_not_installed'
after warm-up: json in sys.modules: True | globals()['json'] is lazy_import
after first use: globals()['json'] is module

Without the warm-up the service managed to print ready and failed on the request; with it, the service failed before that. The last two lines show what the warm-up does to a module that is present: it loads it into sys.modules, but the global name stays a placeholder until the first use, when the placeholder is replaced with the already loaded module. The cost of loading these modules moves back to startup — which is the point of the warm-up.

Checking that a package is present instead of importing it is not enough:

2. INSTALLED IS NOT THE SAME AS IMPORTABLE
------------------------------------------
importlib.metadata.version: 1.0
importlib.util.find_spec:   found
importlib.import_module:    ModuleNotFoundError: No module named 'missing_transitive_dependency'

The broken_dep package has installation metadata and a module spec, but its own import fails on a second-level dependency. The metadata answers "is the package installed", find_spec answers "is the file found"; only the import itself answers "will it import".

An import done for its side effect does not run

A module body runs when the module loads — plugin registration relies on that (import csv_export puts an exporter into a shared registry), and so does patching (import fastjson replaces json.dumps). The names of such modules are never used afterwards, so a lazy import never loads them:

2. IMPORTS DONE FOR A SIDE EFFECT
---------------------------------
plain import                       exporters: ['csv']   json.dumps(1) -> patched:1
lazy import                        exporters: []        json.dumps(1) -> 1
plain import, -X lazy_imports=all  exporters: []        json.dumps(1) -> 1
-X lazy_imports=all + filter       exporters: ['csv']   json.dumps(1) -> patched:1

The third line is the main risk of the global mode. Nothing in the code changed — it still has a plain import csv_export — and the plugin is not registered. There is no error: the registry is simply empty, and the "export to CSV" subcommand disappears from the list. A filter that keeps such modules eager restores the old behaviour — but only if you know them by name.

Circular imports

The classic cycle: a.py does from b import g, b.py does from a import f, and both functions are defined below the imports.

3. CIRCULAR IMPORT
------------------
plain from-import            ImportError: cannot import name 'f' from 'a' (consider renaming '<tmp>/a.py' if it has the same name as a library you intended to import)
lazy from-import             g calls f
plain, -X lazy_imports=all   g calls f
lazy, g() called in a body   ImportError: cannot import name 'f' from 'a' (consider renaming '<tmp>/a.py' if it has the same name as a library you intended to import)

With lazy imports the cycle stops failing: by the time g() is called, both modules have finished loading. But that does not fix the cycle; it only moves the moment it shows up. The last line is the same cycle with g() called in the body of a.py, before f is defined. The use happened during loading, and the error is the same as with a plain import.

Introspection sees placeholders

Until someone uses a name, the module's dictionary holds a lazy_import rather than a module or a class:

4. WHAT INTROSPECTION SEES BEFORE THE FIRST USE
-----------------------------------------------
dir(mod)                     ['Decimal', 'helper', 'json'] | json loaded False, decimal loaded False
vars(mod) value types        {'json': 'lazy_import', 'Decimal': 'lazy_import', 'helper': 'function'}
classes found by vars scan   []
isinstance(.., LazyImportType) True
getattr(mod, 'Decimal')      Decimal | json loaded False, decimal loaded True
vars(mod) value types        {'json': 'lazy_import', 'Decimal': 'type', 'helper': 'function'}
isinstance(Decimal(1), mod.Decimal) True
inspect.getmembers(mod)      | json loaded True, decimal loaded True
vars(mod) value types        {'json': 'module', 'Decimal': 'type', 'helper': 'function'}

The third line is the dangerous one. Code that looks for classes in a module by walking vars(mod) — quite a few plugin and registration systems work that way — does not find Decimal: it is not a type but a placeholder. getattr and inspect.getmembers do trigger loading, and after them the dictionary holds the real objects. isinstance(x, mod.Decimal) works as before, because mod.Decimal is an attribute access. A placeholder can be recognised with types.LazyImportType.

A package of handlers shows how this breaks auto-discovery: handlers/__init__.py imports CsvHandler and JsonHandler with a plain from .csv_handler import …, and the application looks for subclasses of Handler by walking vars(handlers):

3. AUTO-DISCOVERY OF HANDLERS
-----------------------------
plain imports, vars() scan                 found: ['CsvHandler', 'JsonHandler'] loaded by the scan: []
-X lazy_imports=all, vars() scan           found: []                            loaded by the scan: []
-X lazy_imports=all, getattr() scan        found: ['CsvHandler', 'JsonHandler'] loaded by the scan: ['handlers.csv_handler', 'handlers.json_handler']
-X lazy_imports=all + filter, vars() scan  found: ['CsvHandler', 'JsonHandler'] loaded by the scan: []

Under -X lazy_imports=all the vars() walk found no handlers at all, and raised no error. The minimal fix is to walk dir(pkg) and read every name through getattr(pkg, name): that found both. But this fix has a side effect: the walk loaded both handler modules, that is, ran their bodies — and it will load any other lazy name of the package, even an unneeded one. If such a walk goes over someone else's module, that module's code runs along with it. The other fix is a filter that keeps the handler package eager: then the original vars() walk works too.

Four threads, one first use

The module sleeps 0.2 s while loading; four threads start from a barrier and use it right away. Twenty processes per build:

1. FIRST USE FROM FOUR THREADS AT ONCE
--------------------------------------
build 3.15.2t, GIL off, 4 threads, 20 processes
module body runs per process:   [1]
distinct VALUE objects seen:    [1]
global 'slow' after the threads: ['module']
wait of the fastest thread, s:  0.201 to 0.202
wait of the slowest thread, s:  0.202 to 0.203

On the build with the GIL (3.15.2) the result is the same. The module body ran once, and all the threads got the same object. Twenty clean runs do not prove that a failure is impossible; the guarantee comes from the contract — PEP 810: Exactly one thread performs the import and atomically rebinds the importing module's global to the resolved object. That guarantee covers the lazy import mechanism of CPython 3.15 itself. The experiment checked one case: a module without its own import hooks, on two 3.15.2 builds.

What matters in practice is the last two lines: all four threads waited 0.2 s each. The cost of the import did not disappear; it moved from startup to the first request — and fell on every request that arrived while the module was loading.

What -X importtime shows

-X importtime draws a tree: a module sits under the one that imported it. app.py imports json, and main then calls app.dump():

5. WHAT -X IMPORTTIME SHOWS
---------------------------
plain import json in app.py:
  import time:       178 |       5939 |   json
  import time:       954 |       6893 | app
  --- main: app imported, calling app.dump() ---
lazy import json in app.py:
  import time:       964 |        964 | app
  --- main: app imported, calling app.dump() ---
  import time:       195 |       5835 | json

With a lazy import, json moves out from under app: it lands at the top level and is printed after the line where the work begins. Its load time is still visible, but it is no longer attributed to app — and someone looking for "why does app load slowly" will not find it there. A module that is never used does not appear in the list at all; that is why the number of -X importtime lines works as a counter of what was loaded — in the table above it did not change from run to run.

When to switch it on

Lazy imports pay off where a process is short-lived and uses a small part of its dependencies on each call: command-line tools, scripts, hooks, server processes that restart often. They also pay off where there is one heavy and rarely needed dependency — one line makes it lazy. Where the process ends up using almost everything it imported, there is no gain: in the measurement above eight subcommands in a row took as long with the keyword as with plain imports.

They are best avoided where a module is imported for its side effect and such modules cannot be listed by name; where an environment error must surface at startup and mandatory dependencies cannot be warmed up; where first-request latency matters more than startup time. The global mode is more dangerous than the keyword: the keyword is a decision about one line, while all is a decision about the whole tree, other people's libraries included. The selective path — lazy or __lazy_modules__ for specific heavy modules — gives almost the same gain in the startup measurement (48.2 ms versus 41.3 ms for all on --help) and does not touch other people's code.

Before switching on -X lazy_imports=all, go through this checklist; every item is backed by a measurement in this article:

  1. Find imports done for a side effect: plugin registration, function patching, modules that set something up while loading. Under all they do not run until someone uses their names.
  2. Find auto-discovery through vars(), globals() or __dict__: under all it sees placeholders instead of classes.
  3. Keep such modules eager with a sys.set_lazy_imports_filter filter, or do not make them lazy at all.
  4. Run the tests under -X lazy_imports=all and look not only for failures but also for empty registries: a plugin that did not register will not fail a test that does not know about that plugin.
  5. Warm up mandatory dependencies before reporting readiness.

To measure the effect in your own project, use one 3.15 interpreter:

  1. python -X importtime -c "import your_package" with lazy imports and without; count the lines rather than adding up microseconds: the number of modules is reproducible, while the self time is noisy under load.
  2. Process time — many starts in separate processes, median and spread; compare with the empty interpreter of the same version. Measure both a call that needs a small part of the dependencies and one that needs almost all of them.

Reproducing the numbers

uv python install 3.14.10 3.15.2 3.15.2t
./run.sh        # writes runs/*.txt

run.sh sits in the measurement directory together with its description; it runs the timing measurements under a shared lock, flock /tmp/bench.lock, because the machine is shared. Each snippet of contract.py, breakage.py, remedies.py, versions.py and threads.py runs in its own fresh interpreter in a temporary directory; in the records its path is replaced with <tmp>. startup.py takes the paths to two interpreters and prints process time, CPU time, module counts and the resolution of the measurement; firstuse.py prints the time of the import and of the first and second calls of all subcommands. The startup.py and firstuse.py numbers are observations of this machine (2 vCPU Intel Xeon, frequency in the second line of each record, Linux, python-build-standalone); on another machine both the milliseconds and their ratios change. The mechanism does not: which modules are loaded and where the error is raised.

What measured this

The numbers in this article come from these scripts. Each one opens from here, together with the record of the run: what it was measured on, what the results were, and with what spread.

Take to work

  • In command-line tools, make the heavy imports that only one or two subcommands need lazy: in our measurement --help on 3.15.2 went from 97.0 ms to 48.2 ms. But first check whether the module touches those names while it loads — a decorator or a call at module level loads them right away. And do not expect a gain where the process uses almost everything: eight subcommands in a row took 113.0 ms versus 114.3 ms.
  • Keep modules imported for their side effect (plugin registration, patching a function) as plain imports, and before switching on -X lazy_imports=all find them by name and exclude them with a sys.set_lazy_imports_filter filter: otherwise the registry silently ends up empty.
  • Load mandatory dependencies explicitly — from a list, with importlib.import_module — before the service reports ready: otherwise, with a lazy import, a missing module is discovered on the first request that needs it. Checking the metadata or find_spec does not replace this — in the measurement a package that had metadata failed to import.
  • In code that must also run on 3.14, write lazy_modules rather than lazy import: a file with the keyword does not compile at all on 3.14, while the variable simply means nothing there — and in the measurement on 3.15.2 it matched the keyword's time.
  • Measure the effect in your own project by the number of -X importtime lines and by process time over many starts next to the empty interpreter of the same version, not by summing importtime microseconds: the module count is reproducible from run to run, while the self time is noisy under load.

Common misconceptions

Claim

“lazy import defers loading a module until the program really needs it for its work.”

Actually

It defers loading until the first use of the name — and a use at module level counts too. In the article's measurement the lazy tool still loaded logging and dataclasses on --help: the line log = logging.getLogger("tool") and the @dataclass decorator run while the tool itself loads. The gain comes only from names this call did not touch.

Claim

“A lazy import makes the program faster.”

Actually

It moves the cost of the import rather than removing it. If the module is needed, it is loaded at the first use — at the same cost. When the tool ran all eight subcommands, the import with the keyword got 47.5 ms cheaper, the first calls 44.4 ms more expensive, and the whole process took 113.0 ms versus 114.3 ms — a difference below the resolution of the measurement. In the experiment with four threads each one waited 0.2 s for the module to load: the cost moved from startup to the first request and fell on every request that arrived meanwhile. The only work saved is for modules nobody uses in that call.

Claim

“-X lazy_imports=all is safe: the code stays the same, only load timing changes.”

Actually

Behaviour changes: a module imported for its side effect does not run until someone uses its name. In the measurement a plain import csv_export under -X lazy_imports=all left the exporter registry empty, and the json.dumps patch did not take effect — without a single error. The mode reaches other people's libraries too. A sys.set_lazy_imports_filter filter brings the behaviour back, but you need to know such modules by name.

Claim

“On a Python without lazy imports, -X lazy_imports=all causes a startup error, so mixing up versions is impossible.”

Actually

On 3.14.10 the option is accepted silently: Python does not reject an -X option with an unknown name, puts it into sys._xoptions, and the import stays plain. No error, and no laziness either — the same launch command behaves differently on 3.14.10 and 3.15.2. The PYTHON_LAZY_IMPORTS variable does nothing on 3.14.10 either, and sys.set_lazy_imports does not exist there at all.

Claim

“If something breaks, the global mode can be switched off: -X lazy_imports=none.”

Actually

CPython 3.15.2 has two values, all and normal. With -X lazy_imports=none the interpreter does not start at all (“invalid value; expected 'all' or 'normal'”), and sys.set_lazy_imports("none") raises ValueError. The none mode is described in the text of PEP 810 but did not make it into the 3.15.2 release. normal switches off only the global mode: the lazy keyword in the code stays lazy.

Claim

“With lazy imports, try: import x except ImportError will stop catching a missing module.”

Actually

It will not: lazy inside try/except is a SyntaxError, and the compiler marks a plain import there as eager, and it stays eager even under all. In the measurement import csv inside try under -X lazy_imports=all loaded immediately. What stops catching is something else: a lazy import outside try raises ModuleNotFoundError at the first use, and whichever handler happens to be on the way catches it.

Claim

“Lazy imports solve circular imports.”

Actually

They move the moment the cycle shows up. In the measurement an a ↔ b cycle through from … import fails with plain imports and works with lazy ones — because by the time of the call both modules have finished loading. Call a function from the cycle in a module body while it is still loading, and the error is the same as with a plain import: cannot import name 'f' from 'a'.

Knowledge check

Question 1 of 4

A module has lazy import yaml, and the yaml package is not installed. What happens when it runs on 3.15?

Sources & further reading

7 SOURCES

  1. Language reference — Lazy imports, CPython 3.15.2Official documentation. The text at tag v3.15.2, the same version as the measured interpreter. What lazy does: “the module is not loaded immediately at the import statement. Instead, a lazy proxy object is created and bound to the name. The actual module is loaded on first use of that name”. Where it is allowed: “Lazy imports are only permitted at module scope”. When an error is raised: “it is raised at the point where the lazy import is first used, not at the import statement itself”. The same page has the section on __lazy_modules__. CPython tag 3.15.2.https://github.com/python/cpython/blob/v3.15.2/Doc/reference/simple_stmts.rst
  2. What's New In Python 3.15 — PEP 810: Explicit lazy importsOfficial documentation. The text at tag v3.15.2. On the global mode: -X lazy_imports and PYTHON_LAZY_IMPORTS “Both accept two values: all makes all imports lazy by default, and normal (the default) respects the lazy keyword in source code”. On the traceback: “The associated traceback includes both the location where the name was accessed and the original import statement”. CPython tag 3.15.2.https://github.com/python/cpython/blob/v3.15.2/Doc/whatsnew/3.15.rst
  3. The sys module — set_lazy_imports, set_lazy_imports_filter, lazy_modules, CPython 3.15.2Official documentation. The text at tag v3.15.2. On set_lazy_imports: “Library developers should generally not use this function as it affects the runtime execution of applications”. On set_lazy_imports_filter: “This is an advanced feature intended for specialized users who need fine-grained control over lazy import behavior”. On sys.lazy_modules: a set of names “lazily imported in the current interpreter but not yet loaded”, with an implementation note that it may also hold attribute names and items already accessed. CPython tag 3.15.2.https://github.com/python/cpython/blob/v3.15.2/Doc/library/sys.rst
  4. PEP 810 — Explicit lazy importsPEP. Status Final, Python 3.15. On threads: “Reification follows the existing import-lock discipline. Exactly one thread performs the import and atomically rebinds the importing module's global to the resolved object”. On introspection: “calling globals() or accessing a module's __dict__ does not trigger reification”. A discrepancy with the release: the PEP gives sys.set_lazy_imports a third value, “"none" (force all imports to be eager)”, and CPython 3.15.2 does not accept it — the article's run shows this. The text was checked on peps.python.org and in the python/peps repository.https://peps.python.org/pep-0810/
  5. Python/codegen.c and Python/symtable.c — where lazy is forbidden and which imports stay eagerCPython source code. Tag v3.15.2. symtable.c raises SyntaxError “lazy %s not allowed inside try/except blocks”, “… inside functions”, “… inside classes”. codegen.c marks a plain import inside try/except or outside module scope as forced eager, with the comment “force eager import in try/except block”; that is why such imports stay plain under -X lazy_imports=all as well. CPython tag 3.15.2.https://github.com/python/cpython/blob/v3.15.2/Python/codegen.c
  6. Objects/lazyimportobject.c — the lazy_import object and its loadingCPython source code. Tag v3.15.2. The type is called lazy_import; when loading fails, the exception gets an ImportError cause with the text “lazy import of '%U' raised an exception during resolution” and the line of the lazy import statement; when it succeeds, the placeholder in the module's dictionary is replaced through _PyDict_ReplaceItemIf — only if the same placeholder is still there. CPython tag 3.15.2.https://github.com/python/cpython/blob/v3.15.2/Objects/lazyimportobject.c
  7. Lib/site.py and other 3.15.2 standard library modules that import lazily themselvesCPython source code. Tag v3.15.2. site.py has lazy import locale, pkgutil, traceback and warnings; lazy import also appears in argparse, dataclasses, typing, inspect, pathlib, collections and two dozen more modules, and tomllib/_parser.py uses __lazy_modules__. A 3.14-versus-3.15 comparison on the same code therefore measures this too, not only the syntax. CPython tag 3.15.2.https://github.com/python/cpython/blob/v3.15.2/Lib/site.py