Python lazy imports arrived in Python 3.15 (released October 9, 2026): write lazy import json or lazy from pathlib import Path, and the module loads only when your code first uses the name. For CLIs and apps with heavy dependencies, this cuts startup time without moving imports into functions. Measure with -X importtime, mark only the slow imports, and test the error paths, because failures now appear at first use instead of at import time.
This guide covers the syntax, where lazy is not allowed, how to find which imports to change, the global -X lazy_imports switch, the filter API, and a pattern that keeps code working on Python 3.14 and older. Facts come from the Python 3.15 documentation and PEP 810, checked on October 21, 2026.
What Python lazy imports change
A normal import finds, reads, compiles and runs the module right away. In a large app, that can add up to seconds before main() even starts, and much of it is for code paths a given run never touches (think --help).
With PEP 810, lazy is a new soft keyword. A lazy import binds the name to a lightweight proxy. The first time you use that name, Python does the real import and swaps the proxy for the module or object.
import x | lazy import x | |
|---|---|---|
| When the module runs | At the import line | At first use of x |
| Import-time side effects | Immediately | Deferred to first use |
| Missing module error | At the import line | At first use (traceback shows both lines) |
Appears in sys.modules | Immediately | After first use |
lazy is a soft keyword, so existing variables or functions named lazy keep working.
How to use lazy imports in Python 3.15
Step 1: Install Python 3.15 and confirm the version
Get 3.15 from python.org or your usual version manager, then check it:
python3.15 --version
python3.15 -c "import sys; print(sys.get_lazy_imports())"The second command prints the current lazy imports mode. normal is the default, which means only imports marked with lazy are lazy.
Step 2: Write your first lazy import
The two forms mirror regular imports:
lazy import json
lazy from pathlib import Path
print("Starting up...") # json and pathlib are not loaded yet
data = json.loads('{"key": "value"}') # json is imported here
p = Path(".") # pathlib is imported hereFor lazy from, the first access loads the module and resolves only the name you accessed.
Step 3: See the deferral with a slow module
Create slowmod.py, a module that is slow and noisy on import:
import time
print("slowmod: loading...")
time.sleep(1)
def hello():
return "hello from slowmod"Then import it lazily in demo.py:
import sys
lazy import slowmod
print("1. app started")
print("2. in sys.modules?", "slowmod" in sys.modules)
print("3.", slowmod.hello())
print("4. in sys.modules?", "slowmod" in sys.modules)Run python3.15 demo.py. Line 1 prints immediately, line 2 prints False, then slowmod: loading... appears, followed by line 3 and True on line 4. The one-second sleep moved from startup to the first call.
Where lazy is not allowed
The compiler rejects lazy in several places with a SyntaxError:
| Code | Allowed? |
|---|---|
lazy import x at module top level | Yes |
| Inside a function or class body | No |
Inside try / except / finally | No |
lazy from x import * | No |
lazy from __future__ import ... | No |
The try rule matters most in practice. The common optional-dependency pattern stays eager:
try:
import ujson as json # must stay a normal import
except ImportError:
import jsonThat makes sense: a lazy import could not raise ImportError at that line, so the except branch would never run.
Find which imports to make lazy
Do not add lazy everywhere at once. Measure first. Python has shipped an import profiler since 3.7:
python3.15 -X importtime -c "import myapp.cli" 2> import.logEach line shows the module name, its self time and its cumulative time in microseconds (nested imports included). Sort by cumulative time to find the biggest chunks:
sort -t'|' -k2 -n -r import.log | head -20Good candidates:
- Heavy libraries used by only some commands (data, plotting, cloud SDKs, ML frameworks).
- Modules used only in rarely hit paths such as error reporting or export.
- Modules imported only for type annotations.
Then compare wall-clock startup before and after on the command users run most:
time python3.15 -m myapp --help View PlantUML source
@startuml
skinparam shadowing false
skinparam defaultFontSize 14
start
:Profile with -X importtime;
:Pick heavy, rarely used imports;
:Add lazy keyword;
:Run tests that use each module;
if (Startup faster and tests pass?) then (yes)
:Keep the change;
else (no)
:Revert that import;
endif
stop
@endumlA real-world pattern: a fast CLI
A typical CLI pays for every subcommand's dependencies even when the user only asks for --help. Lazy imports keep imports at the top of the file, where readers and linters expect them, and still defer the cost. Here is myapp/cli.py:
import argparse
lazy import pandas as pd
lazy from myapp.report import build_report
lazy from myapp.upload import upload_to_bucket
def main():
parser = argparse.ArgumentParser(prog="myapp")
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("report").add_argument("csv")
sub.add_parser("upload").add_argument("path")
args = parser.parse_args()
if args.cmd == "report":
df = pd.read_csv(args.csv) # pandas loads only here
print(build_report(df))
elif args.cmd == "upload":
upload_to_bucket(args.path) # upload module loads only here
if __name__ == "__main__":
main()Before 3.15 you would move those imports inside each branch to get the same effect. That still works, but it scatters imports and hides dependencies.
Replace if TYPE_CHECKING blocks
PEP 810 notes that lazy imports remove the common need for TYPE_CHECKING guards. An import used only in annotations never gets touched at runtime, so a lazy import costs almost nothing:
Before:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from myapp.models import InvoiceAfter (Python 3.15+):
lazy from myapp.models import Invoice
def total(invoice: Invoice) -> float:
...Check that your type checker and linter versions understand the lazy keyword before you switch; older releases will report a syntax error.
Supporting Python 3.14 and older: __lazy_modules__
The lazy keyword is a syntax error on older interpreters. If your package still supports them, declare the modules instead:
__lazy_modules__ = ["json", "pathlib"]
import json # lazy on 3.15+
import os # still eager
import pathlib # lazy on 3.15+Python 3.15 treats regular imports of the listed fully qualified names as if they had the lazy keyword. Older versions ignore the variable, so the same file runs everywhere (eagerly on old versions). Define __lazy_modules__ before the imports it should affect.
Make all imports lazy: -X lazy_imports and the filter
To test how much an entire app gains, switch the global mode:
python3.15 -X lazy_imports=all -m myapp --help # command-line option
PYTHON_LAZY_IMPORTS=all python3.15 -m myapp --help # environment variableBoth accept two values: all (top-level imports become potentially lazy) and normal (the default, only the lazy keyword counts). The same switch is available at runtime as sys.set_lazy_imports("all"), and a filter lets you decide per module:
import sys
def myapp_filter(importing, imported, fromlist):
# True = allow lazy, False = force eager
return imported.startswith("myapp.")
sys.set_lazy_imports_filter(myapp_filter)
sys.set_lazy_imports("all")
import myapp.slow_module # lazy (matches filter)
import json # eager (filter returns False)The filter receives the importing module's name, the imported module's name and the fromlist (or None for a plain import). Pass None to sys.set_lazy_imports_filter() to clear it.
The sys docs say these global controls are meant for application owners. Library authors should not call them, because they change how the whole program runs. In a library, use the lazy keyword or __lazy_modules__ instead.
Gotchas before you ship
View PlantUML source
@startuml
skinparam shadowing false
skinparam defaultFontSize 14
rectangle "lazy import x" as L
rectangle "Proxy bound to x" as P
rectangle "Real import of x" as R
rectangle "Proxy stays" as S
L --> P
P --> R : use x / x.attr / getattr
P --> S : globals() / __dict__
@enduml- Errors move. A typo in a lazy module name raises at first use, maybe deep inside a request handler. The traceback includes the original import line, but your tests must actually exercise that code path. Add a smoke test that touches every lazily imported name.
- Side effects move. Code that registers plugins, signal handlers or ORM models on import now runs at first use. If a registry depends on import-time registration, keep those imports eager or call an explicit setup function. PEP 810 calls out registry patterns as a risk.
globals()andmodule.__dict__show proxies. Reading them does not trigger the import. Code that walks a module's namespace can seetypes.LazyImportTypeobjects instead of modules. Check for that type if you need to.- Submodules. Import submodules explicitly (
import pkg.sub) rather than relying onpkg.subbeing set as a side effect of some other import. - Already-loaded modules are shared. If something imported the module eagerly first, the lazy name resolves to the same module object.
- Thread timing. The first use can now happen on any thread, at any time. If a module has expensive or order-sensitive setup, keep it eager and load it at startup.
Run your test suite on 3.15 in CI
Add 3.15 to your matrix before you add lazy, so you know any new failures come from the keyword. If you pin your CI actions, see how to lock GitHub Actions workflow dependencies.
strategy:
matrix:
python-version: ["3.13", "3.14", "3.15"]
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
- run: python -m pip install -e ".[test]"
- run: python -m pytestIf your 3.15 job passes but older versions fail with SyntaxError: invalid syntax on lazy import, switch those files to __lazy_modules__. Running Node services alongside Python? The Node.js 26 LTS upgrade checklist covers the same kind of runtime bump on the JavaScript side.
FAQ
Are Python lazy imports on by default in 3.15? No. The default mode is normal: only imports you mark with lazy (or list in __lazy_modules__) are lazy. -X lazy_imports=all or PYTHON_LAZY_IMPORTS=all makes top-level imports lazy across the program.
Can I use lazy import inside a function? No. It raises SyntaxError. Lazy imports are allowed only at module scope, and not inside try/except/finally or class bodies. Inside a function, a plain local import is already deferred until the function runs.
Does lazy import make my code run faster overall? It speeds up startup and avoids loading modules a run never uses. The import cost is not removed; it moves to the first use. Long-running servers that use everything see little gain, while CLIs and serverless cold starts benefit most.
Will lazy imports break my library on Python 3.14? The lazy keyword will, because older parsers do not know it. Use __lazy_modules__ with normal import statements instead; older versions ignore it and import eagerly.
How do I check whether a name is still a lazy proxy? Look it up without using it, for example type(globals()["slowmod"]) is types.LazyImportType. Reading globals() does not trigger the import, while slowmod.anything does.
Summary
Install Python 3.15, run -X importtime on your slowest entry point, and mark the heavy, rarely used imports with lazy. Keep optional-dependency try blocks and import-time registries eager, add a smoke test that touches every lazy name, and use __lazy_modules__ if you still support older Python versions.
Written on October 21, 2026, based on the Python 3.15.0 documentation. Check the official sources below for changes in later 3.15.x releases.
References
- Python documentation, What's New in Python 3.15 (lazy imports section) — docs.python.org (checked Oct 21, 2026)
- PEP 810, Explicit lazy imports — peps.python.org (checked Oct 21, 2026)
- Python documentation, sys module: set_lazy_imports, get_lazy_imports, set_lazy_imports_filter — docs.python.org (checked Oct 21, 2026)
- Python documentation, Command line and environment: -X lazy_imports, PYTHON_LAZY_IMPORTS, -X importtime — docs.python.org (checked Oct 21, 2026)
- Python downloads — python.org (checked Oct 21, 2026)
- actions/setup-python and actions/checkout releases (v7) — github.com (checked Oct 21, 2026)


2 thoughts on “Python Lazy Imports in 3.15: How to Speed Up Startup”