
Every Python program pays an invisible toll before the first line of real work runs: its imports. Import a big library at the top of a file and Python locates it, loads its bytecode (or compiles its source when necessary), and executes its top-level code, whether or not your program ever touches it. For command-line tools, test suites, and large applications, that adds up.
Until now, the options were moving imports inside functions, using importlib to load modules on demand, or relying on third-party packages. Python 3.15 adds a built-in alternative: the lazy soft keyword from PEP 810. Python 3.15.0 was released on October 9, 2026, and the feature is included in the latest maintenance release, Python 3.15.2.
This post explains how lazy imports work, compares three approaches in a small CLI application, and examines the performance results from running the actual code on Python 3.15.2.
The one-keyword fix
import sys
lazy import json
lazy from pathlib import Path
print("json" in sys.modules) # False: not loaded yet
print("pathlib" in sys.modules) # False: not loaded yet
data = json.dumps({"hello": "world"}) # First use loads json
print("json" in sys.modules) # True
location = Path(".").resolve() # First use loads pathlib
print("pathlib" in sys.modules) # TrueWhen you write lazy import json, Python binds the name json immediately, but to a lightweight proxy object. The real import happens the first time you use that name. After the import succeeds, the name is rebound to the actual module and behaves like a normal import.
A few details:
lazyis a soft keyword. It only has special meaning immediately before an import statement, so it remains a legal variable name elsewhere.lazy from m import a, bbinds each imported name lazily. The first access to either name loads the entire module, but only the accessed name is resolved. Other imported names remain lazy until used.Laziness is local, not recursive. Marking
pandasas lazy delays loading pandas itself. It does not automatically make pandas' own imports lazy. When pandas loads, its regular import process runs normally.Everything else about the import machinery stays the same. Python still uses the same import hooks, loaders, and module objects. What changes is the timing of the import.
The example above was also tested directly on Python 3.15.2 using python3.15 -S. Both modules remained absent from sys.modules before first use and appeared after their respective names were accessed.
The benchmark: before and after
To measure the effect, I used a small CLI application called reportkit with four commands:
version: displays the application version.stats: reads a CSV file using pandas and NumPy.fetch: makes an HTTP request using requests.serve: starts a Flask application.
This is a useful shape for a command-line tool because running --help or version should not require loading a web framework and a data-analysis stack.
Before: everything imported at the top
import sys
import click
import flask
import numpy as np
import pandas as pd
import requestsEvery command pays the cost of loading all five dependencies, even when it needs only one or none of the heavy libraries.
After: the same imports, marked lazy
On Python 3.15, the imports become:
import sys
import click
lazy import flask
lazy import numpy as np
lazy import pandas as pd
lazy import requestsclick stays a regular import because the command-group and command decorators use it while the application file is being loaded.
The remaining dependencies are declared at the top but loaded only when their corresponding functionality is accessed.
What I measured
Unlike an earlier proxy experiment using function-local imports on Python 3.12, these measurements were collected directly on Python 3.15.2.
Test environment:
Python 3.15.2
Apple Silicon MacBook Air running macOS
click 8.5.0
pandas 3.0.6
NumPy 2.5.4
requests 2.34.2
Flask 3.1.3
I compared three implementations:
Eager imports: all dependencies imported at the top.
PEP 810 lazy imports: heavy dependencies marked with
lazy.Function-local imports: heavy dependencies imported inside the commands that need them.
Each implementation ran in a separate Python process. I performed three warm-up runs followed by 30 measured runs per command, rotating the execution order to reduce ordering bias.
The stats command used a small five-row CSV file. The numbers are specific to this application, its dependencies, and my test machine, not universal performance guarantees.
Results: version command
The version command uses none of the heavy libraries.
Implementation | Median startup | Standard deviation |
|---|---|---|
Eager imports | 505.73 ms | 34.86 ms |
PEP 810 lazy | 52.42 ms | 2.82 ms |
Function-local imports | 52.69 ms | 6.06 ms |
PEP 810 reduced startup time by 89.6% compared with eager imports.
The application went from approximately 506 ms to 52 ms because Flask, NumPy, pandas, and requests were never loaded.
Results: stats command
The stats command needs both pandas and NumPy but does not need Flask or requests.
Implementation | Median startup | Standard deviation |
|---|---|---|
Eager imports | 490.70 ms | 76.17 ms |
PEP 810 lazy | 368.44 ms | 33.27 ms |
Function-local imports | 377.34 ms | 19.50 ms |
PEP 810 reduced startup time by 24.9%.
The savings are smaller because pandas and NumPy still have to be imported. Only Flask and requests can be skipped.
Two things stand out:
The win scales with what you skip. The
versioncommand needs none of the heavy libraries, so most of their startup cost disappears. Thestatscommand still needs pandas and NumPy, so the savings are limited to the dependencies it does not use.Native lazy imports and function-local imports perform similarly. In the
versiontest, their median times differed by just 0.27 ms. In thestatstest, the difference was 8.90 ms, which is small relative to the observed run-to-run variation. The important advantage of PEP 810 is that dependencies remain visible at the top of the file without being loaded unnecessarily.
The initial import checks also confirmed the behavior. All four heavy libraries appeared in sys.modules for the eager implementation. None appeared for the PEP 810 or function-local implementations before the relevant command accessed them.
Where the import cost goes
Lazy imports do not eliminate the cost of importing a module. They move it to the point where the module is first needed.
To verify this separately, I measured the setup phase and the first stats operation in three implementations. Each version ran 30 times after three warm-up runs.
The phase timer started after Python had initialized and click had been imported. The setup measurement covered the NumPy and pandas imports in the eager version, the lazy declarations in the PEP 810 version, or no heavy imports in the function-local version.
Measurement | Eager | PEP 810 lazy | Function-local |
|---|---|---|---|
Import setup | 291.84 ms | 0.00 ms | 0.00 ms |
First | 1.44 ms | 294.31 ms | 287.94 ms |
Total measured time | 293.44 ms | 294.32 ms | 287.95 ms |
Values are medians in milliseconds. Setup values of 0.00 ms are rounded to two decimal places.
The eager implementation pays for NumPy and pandas before the operation starts. As a result, the first stats operation takes only about 1.44 ms.
With PEP 810, setup is almost instantaneous, but the first operation takes approximately 294 ms because it triggers the imports.
Function-local imports behave similarly: their cost appears when the function is called.
The total measured times are close. The phase measurements also showed substantial run-to-run variation, so they are best used to demonstrate where the cost is paid, not to claim that one implementation is intrinsically faster than another.
This is the key distinction: lazy imports improve startup when dependencies are not immediately needed. They do not make importing those dependencies intrinsically faster.
Finding what to make lazy
Don't guess. Python can tell you what your imports cost:
python -X importtime app.py version 2> imports.logEach line shows the import's own time and its cumulative time, in microseconds. Look for expensive top-level imports, then ask: does the most common execution path really need them?
A large cumulative import time is a useful starting point, but the important question is whether that dependency is needed on the path your users actually run.
For example, if your CLI has ten commands but only two use pandas, loading pandas for all ten commands is probably unnecessary.
Profile first, then mark imports lazy where the application can genuinely defer them.
Rules and gotchas
Where lazy is allowed. Lazy imports are permitted only at module scope. Using the keyword inside a function, class body, or try/except/finally block raises a SyntaxError. So do lazy from m import * and lazy from __future__ import .... Star imports and future imports cannot be lazy.
Errors move to first use. A missing module or an invalid imported name now fails when the lazy name is first accessed rather than when the import statement is encountered.
lazy from json import dumsp # Typo: should be dumps
print("App started") # This can run
result = dumsp({"key": 1}) # ImportError raised herePython also provides an exception chain that helps identify both the original lazy import and the location where the name was first accessed.
Side effects move too. If importing a module registers a plugin, patches something, or populates a registry, that now happens at first use, or possibly never. This can break applications that depend on import-time registration. Prefer an explicit discovery or initialization function that you call when needed.
lazy from m import Name loads all of m. Python cannot execute only one part of a module. Accessing Name for the first time executes the entire module, even though only the requested name is resolved.
Circular imports aren't magically fixed. Lazy imports can defer when a circular dependency is encountered, but they do not remove the underlying dependency cycle. Import-time initialization that accesses unresolved names can still fail.
Import submodules explicitly. If you need foo.bar, import the submodule explicitly with import foo.bar. Importing foo does not guarantee that foo.bar has been loaded.
Introspection doesn't always force loading. Reading a module's __dict__ or calling globals() returns the raw namespace rather than automatically resolving lazy proxies. Before first use, introspection can therefore expose proxy objects such as types.LazyImportType.
Controls beyond the keyword
Python 3.15 provides several ways to control lazy imports.
Tool | What it does |
|---|---|
| Make an individual import lazy. |
| Make specified regular imports lazy in Python 3.15+. |
| Make all eligible top-level imports potentially lazy. |
| Enable the same global mode through an environment variable. |
| Change or inspect the global mode at runtime. |
| Decide whether individual imports should remain lazy. |
Supporting older Python versions
The lazy keyword itself is new syntax. Python versions before 3.15 cannot parse it.
For projects supporting both older Python versions and Python 3.15+, use __lazy_modules__ with regular imports:
__lazy_modules__ = ["numpy", "pandas"]
import numpy as np
import pandas as pdOn Python 3.15 and later, these imports can be lazy. On older versions, the declaration is ignored and the imports behave normally.
This makes __lazy_modules__ a useful compatibility bridge when you cannot require Python 3.15 for every user.
The global switch and import filter are intended primarily for application developers and framework authors. The PEP discourages libraries from changing the global mode because it affects the behavior of the entire application.
Practical tips
Move function-level imports back to the top when appropriate. If you were hiding imports inside functions purely to avoid startup costs, PEP 810 lets you declare those dependencies at the top with lazy.
# Before: import inside a function
def process(data):
import json
return json.dumps(data)
# After: explicit lazy import
lazy import json
def process(data):
return json.dumps(data)This keeps dependencies visible without paying their import cost immediately.
Reconsider TYPE_CHECKING guards. Imports used only in annotations can often be marked lazy instead of being hidden behind TYPE_CHECKING.
lazy from collections.abc import Sequence, Mapping
def process(items: Sequence[str]) -> Mapping[str, int]:
...The module does not need to load just because the import is declared. However, code that later resolves or inspects annotations may trigger the import.
Expect first-use latency. Lazy imports move the cost; they do not remove it. In a server, the first request that touches a lazy dependency pays the import cost. When first-request latency matters, access the relevant lazy names during application startup to load them before traffic arrives.
When it helps most
Command-line tools with many subcommands, where
--help,version, or simple operations should not load every dependency.Test suites that import large dependency graphs but execute only a small part of the application.
Large applications with optional subsystems, plugins, or features that are not needed on every run.
Annotated code with imports used only for type information.
If your program uses every import on every run, lazy imports will not save much startup time. They will still change when errors and side effects occur, so adopt them where profiling shows a real benefit.
Try it on your own app
Start by measuring the imports in your application:
python -X importtime app.py version 2> imports.logThen compare eager imports, PEP 810 imports, and function-local imports on the same Python version and machine.
A simple benchmark harness for a CLI application is:
import statistics
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent
APPS = {
"Eager": "app_eager.py",
"PEP 810 Lazy": "app_lazy.py",
"Function Local": "app_local.py",
}
COMMANDS = {
"version": ["version"],
"stats": ["stats", "sample.csv"],
}
RUNS = 30
WARMUPS = 3
def measure(app, args):
start = time.perf_counter()
result = subprocess.run(
[sys.executable, str(ROOT / app), *args],
cwd=ROOT,
capture_output=True,
text=True,
)
elapsed = (time.perf_counter() - start) * 1000
if result.returncode != 0:
raise RuntimeError(result.stderr)
return elapsed
for command, args in COMMANDS.items():
results = {name: [] for name in APPS}
for _ in range(WARMUPS):
for name, app in APPS.items():
measure(app, args)
for i in range(RUNS):
names = list(APPS)
shift = i % len(names)
names = names[shift:] + names[:shift]
for name in names:
results[name].append(
measure(APPS[name], args)
)
baseline = statistics.median(results["Eager"])
print(f"\n===== {command.upper()} =====")
for name, values in results.items():
median = statistics.median(values)
deviation = statistics.stdev(values)
change = (1 - median / baseline) * 100
print(
f"{name:16} "
f"median={median:8.2f} ms "
f"stdev={deviation:6.2f} ms "
f"change={change:+6.1f}%"
)Run it on commands your users actually execute, such as --help, version, or a lightweight operation. Keep the Python version, dependency versions, environment, and workload consistent between implementations.
Wrap-up
lazy turns a long-standing workaround into a built-in language feature. Instead of hiding imports inside functions, you can keep dependencies visible at the top of your file and defer loading until they are needed.
In my Python 3.15.2 CLI benchmark, lazy imports reduced the median startup time of a command that needed none of the heavy libraries from approximately 506 ms to 52 ms, an 89.6% reduction.
For a command that still needed pandas and NumPy, startup time fell by 24.9% because only the unused Flask and requests dependencies could be skipped.
The first-use experiment confirmed the trade-off: the lazy version avoided almost all import setup initially, but paid approximately 294 ms when the first operation accessed pandas and NumPy.
The practical lesson is simple: profile your imports, mark expensive and rarely used dependencies lazy, watch for import-time side effects, and measure both startup and first-use latency.
For the full details, see the Python 3.15 release notes, the Python 3.15.2 language reference, and PEP 810.
Comments0
Log in to join the discussion.
No comments yet.