According to recent reports, 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.

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:. (Related: How to train a newly introduced language model from scr...)

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). (Related: The Reformer - Pushing the limits of language modeling...)

It has been revealed that 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 claims 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.

Sources indicate that 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.

Profile the import of the app module twice, once as written and once with the global switch:.

Industry observers note that -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 reveals 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.

Sources indicate that 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.

Here is the version that bites. The domain defines a port and a use case:.

The adapter imports the SDK at the top, the ordinary way:.

And the app builds the adapter per request through a dependency:.

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.

The health check never touches the adapter, so it stays green while every request that does touch it fails.

According to recent reports, the fix follows the boundaries you already drew in a hexagonal app. Three rules.

Sources indicate that 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.

It has been revealed that 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:.

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.

Sources indicate that 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:.

Industry observers note that 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:.

Recent findings suggest that 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.

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.

Industry observers note that 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.

→ Read original article