- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples โ every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub โ an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
Your FastAPI service boots faster than it ever has. The readiness probe goes green and the deploy finishes quietly. Ten minutes later the first customer tries to pay, and the payment endpoint returns a 500. The cause is an ImportError for a package that fell out of the lockfile two commits ago. The boot never noticed, because the boot never loaded it.
That is the trade you sign up for with lazy import. PEP 810 shipped in Python 3.15, released on 9 October 2026. A lazy import binds a proxy and loads the real module the first time you touch the name. Any load error surfaces at that touch, too. You get the faster startup. You also get a new place for failures to land, and in a hexagonal app that place is usually an adapter.
What lazy import does, precisely
lazy is a soft keyword that only means something directly before import or from. Per the language reference, the statement creates a lazy proxy object, binds it to the name, and loads the module on first use of that name. This is adapted from the reference's example:
lazy import json
import sys
print("json" in sys.modules) # False: not loaded yet
result = json.dumps({"hello": "world"})
print("json" in sys.modules) # True: loaded on first use
Four details from the PEP matter for production code. With lazy from module import name, first access runs the whole module but resolves only that one name. If loading fails, the proxy stays in place and the next use retries the whole import. The error is chained so the traceback shows both the import line and the line that touched the name. And import-time side effects in the lazy module run at first use, not at import time.
There are limits on where you can write it. lazy is allowed only at module scope; inside a function, a class body, or a try/except/finally block it is a SyntaxError, and star imports and __future__ imports can't be lazy (reference).
Then there are the switches that apply it to code you didn't edit. -X lazy_imports=all or PYTHON_LAZY_IMPORTS=all makes imports lazy by default, and normal, the default, respects only the keyword (command-line docs). The PEP says the global mode covers module-level imports everywhere except inside try blocks and star imports.
At runtime, sys.set_lazy_imports() sets the mode. sys.set_lazy_imports_filter() takes a callable (importing_module, imported_module, fromlist) -> bool. Return True to allow lazy, False to force eager. The PEP text also describes a none mode, but the 3.15 docs for -X lazy_imports, PYTHON_LAZY_IMPORTS and sys.set_lazy_imports() list only all and normal, so don't build on none.

A lazy import binds a placeholder now and fetches the real module the first time the name is used.
Measure the startup before you change anything
Take a small hexagonal FastAPI app. The domain is plain Python. The adapters pull in vendor SDKs such as stripe and boto3. The app module wires them together.
app/
domain/orders.py # stdlib only: PaymentPort, place_order
adapters/stripe_payments.py # import stripe
adapters/s3_receipts.py # import boto3
main.py # FastAPI app, composition root
Profile the import of the app module twice, once as written and once with the global switch:
python -X importtime -c "import app.main" 2> eager.log
python -X lazy_imports=all -X importtime \
-c "import app.main" 2> lazy.log
sort -t'|' -k2 -n eager.log | tail -15
-X importtime writes one line per import to stderr with a self time (excluding nested imports) and a cumulative time (including them). As CPython core developer Inada Naoki shows in his startup-time write-up, the header reads import time: self [us] | cumulative | imported package, the numbers are microseconds, and indentation shows nesting. The sort on the second | field puts the biggest cumulative costs at the bottom.
In eager.log, look at the cumulative column for the SDK lines. In lazy.log, a module that nothing touches during import app.main is never loaded, so it shouldn't show up at all. I haven't run this against your app, and the gap depends on SDK versions, disk cache and how much your own code touches at import time. The PEP's authors report that lazy imports "can reduce startup time by 50-70% in practice"; that's their figure, and yours will land wherever your SDKs and import-time work put it. One more caveat from the docs: -X importtime output may be broken in multi-threaded applications, so profile a plain -c "import ...", not a running server.
Where does the win pay off? Mostly in CLI entry points, test collection, and worker cold starts, the places that import your package and touch little of it. A server that boots once per deploy gains less.
Green boot, red first request
Here is the version that bites. The domain defines a port and a use case:
# app/domain/orders.py
import uuid
from typing import Protocol
class PaymentPort(Protocol):
def charge(self, order_id: str, amount_cents: int) -> None: ...
def place_order(amount_cents: int, payments: PaymentPort) -> str:
if amount_cents <= 0:
raise ValueError("amount must be positive")
order_id = uuid.uuid4().hex
payments.charge(order_id, amount_cents)
return order_id
The adapter imports the SDK at the top, the ordinary way:
# app/adapters/stripe_payments.py
import stripe
class StripePayments:
def __init__(self, api_key: str) -> None:
self._api_key = api_key
def charge(self, order_id: str, amount_cents: int) -> None:
stripe.PaymentIntent.create(
amount=amount_cents,
currency="eur",
metadata={"order_id": order_id},
api_key=self._api_key,
)
And the app builds the adapter per request through a dependency:
# app/main.py
import os
from fastapi import Depends, FastAPI
from app.domain.orders import PaymentPort, place_order
lazy from app.adapters.stripe_payments import StripePayments
app = FastAPI()
def get_payments() -> PaymentPort:
return StripePayments(os.environ["STRIPE_API_KEY"])
@app.get("/health")
def health() -> dict[str, str]:
return {"status": "ok"}
@app.post("/orders")
def create_order(
amount_cents: int,
payments: PaymentPort = Depends(get_payments),
) -> dict[str, str]:
return {"order_id": place_order(amount_cents, payments)}
Now drop stripe from the image. The server imports app.main, the domain loads, and StripePayments is a proxy. /health returns 200 because it never touches the proxy. The first POST /orders calls get_payments, which touches StripePayments, which runs the adapter module, which hits import stripe and fails. Because a failed reification leaves the proxy in place and retries on the next use, every request to /orders fails the same way while /health stays green.
You don't need the lazy keyword for this to happen. Run the same code without the lazy keyword under -X lazy_imports=all and the import of app.adapters.stripe_payments in main.py becomes potentially lazy too. An ops flag in a Dockerfile can move your failure from boot to first request without a code change.
At least the traceback shows both lines. The PEP's example, with a typo in a lazy from json import dumsp, prints two chained tracebacks. The first points at the import line and ends ImportError: lazy import of 'json.dumsp' raised an exception during resolution. The second points at the line that used the name and ends ImportError: cannot import name 'dumsp' from 'json'. Did you mean: 'dump'?. You get both locations, just in the request log instead of the deploy log.

The health check never touches the adapter, so it stays green while every request that does touch it fails.
Keep the core eager, let adapters be lazy, load them once on purpose
The fix follows the boundaries you already drew in a hexagonal app. Three rules.
The domain never needs lazy imports. It imports the standard library and your own code, so it is cheap to load eagerly, and an error in it should fail the boot. If the domain only boots fast with lazy imports, it is importing something that belongs behind a port.
Adapters may load lazily. If you want the global switch, scope it with a filter in the entry point, before anything imports the app. This mirrors the filter example in the 3.15 release notes:
# run.py
import sys
def adapters_only(importing, imported, fromlist):
return imported.startswith("app.adapters")
sys.set_lazy_imports_filter(adapters_only)
sys.set_lazy_imports("all")
import uvicorn # noqa: E402
import app.main # noqa: E402
uvicorn.run(app.main.app)
Third-party packages and the domain stay eager. Only the adapter modules become proxies, and the SDK inside an adapter loads when the adapter does.
Load every adapter once, on purpose. In the server, that place is the composition root. Build adapters in the FastAPI lifespan, whose code before yield runs before the application starts taking requests:
# app/main.py (composition root version)
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from app.domain.orders import PaymentPort
lazy from app.adapters.stripe_payments import StripePayments
@asynccontextmanager
async def lifespan(app: FastAPI):
key = os.environ["STRIPE_API_KEY"]
app.state.payments = StripePayments(key)
yield
app = FastAPI(lifespan=lifespan)
def get_payments(request: Request) -> PaymentPort:
return request.app.state.payments
A missing SDK now fails at startup, before any customer reaches /orders. Code that imports app.main without starting the server still skips the SDK, and that was the startup win you wanted in the first place.
That holds when the SDK import inside the adapter is eager, as it is in normal mode or behind the run.py filter. Under a bare -X lazy_imports=all, import stripe in the adapter is lazy as well, and building StripePayments never touches it. In that setup, keep the filter, or run the smoke test's force_load over the adapters inside the lifespan too.
Then add a smoke test that forces every adapter to load, including names an adapter imported lazily itself. A module's __dict__ holds lazy proxies without resolving them (PEP), and types.LazyImportType.resolve() reifies one and returns the real object:
# tests/test_adapters_load.py
import importlib
import pkgutil
import types
import app.adapters
def force_load(name: str) -> None:
module = importlib.import_module(name)
for value in list(vars(module).values()):
if isinstance(value, types.LazyImportType):
value.resolve()
def test_every_adapter_loads():
for info in pkgutil.walk_packages(
app.adapters.__path__, prefix="app.adapters."
):
force_load(info.name)
Run it with the same flags production uses, for example python -X lazy_imports=all -m pytest tests/test_adapters_load.py. A dropped dependency or a renamed imported name now fails CI. It won't catch an SDK attribute that is only touched at call time, such as stripe.PaymentIntent; that still needs a test that calls the adapter. With the filter or in normal mode, the lifespan catches a missing SDK at deploy if CI didn't run.

Keep the core eager and cheap, let the adapters defer, and turn them all on once where you choose.
Where this changes nothing
Some code you can leave alone. The optional-dependency idiom, try: import orjson with an except ImportError fallback, keeps working eagerly: lazy is a syntax error inside try, and the global mode skips try blocks. Imports inside functions stay as they are, because lazy isn't allowed there either.
If you maintain a library, the sys docs say library developers should generally not call sys.set_lazy_imports(), since it changes how the whole application runs. Use the keyword or __lazy_modules__ for your own heavy imports, and leave the global switch to the application's entry point.
Start with the smoke test. It's about twenty lines, and in normal mode it already fails on a dropped dependency, before you write a single lazy.
If this was useful
The rule this post ends on is to keep the core free of heavy imports, push the SDKs out to the adapters, and wire everything in one composition root. That design idea is what Hexagonal Architecture in Python is about. The book doesn't cover lazy imports. It builds one async FastAPI + SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered, vertical slice) and measures them, which is how you end up with boundaries that make a change like PEP 810 easy to adopt. Every listing runs from the free companion repo.

Top comments (1)
Gabriel, the 'green boot, red first request' section is the one that will save someone a 3 a.m. page โ /health returning 200 while every POST /orders fails, with the proxy retrying the same failed import on each request, is exactly the kind of failure that looks like a flaky downstream until you read the traceback. The 50โ70% startup figure from the PEP authors is the headline, but the part I keep coming back to is the honesty about it: the gain depends on what your app actually touches at import, and the -X importtime before/after is the only way to know your number. The lifespan composition-root fix plus the ~20-line smoke test that forces every adapter to load feels like the right pairing โ fail at startup or fail in CI, never on the first real request. One question: with the filter in run.py scoping lazy imports to app.adapters, do you also keep -X lazy_imports=all out of the Dockerfile entirely, or do you set it there and rely on the filter to tame it?