# Python 3.15 Lazy Imports: Faster Startup With the lazy Keyword

> How PEP 810 lazy imports work in Python 3.15: syntax, restrictions, __lazy_modules__, where startup time drops, and the pitfalls to check before adopting it.

Python 3.15 added a way to say "import this module, but only when I actually use it". The new `lazy` keyword, from PEP 810, binds the name straight away and postpones the real import until the first time the name is touched. For command-line tools, serverless functions and large web apps with heavy dependency trees, that can cut startup time without restructuring the code.

It is not free, though. Import-time side effects move, import errors show up later, and the feature is restricted to module scope. This article covers how it works, where it helps, and what to check before you switch it on.

> **Verification note.** I could not open python.org (the PEP and the official "What's New in Python 3.15" page) from the environment I used to research this article, so the details below come from search-result summaries of those pages and from secondary write-ups. Where I could not confirm something, such as exact environment variable names, I say so. I have not run the code below on Python 3.15. Check the [What's New page](https://docs.python.org/3.15/whatsnew/3.15.html) and [PEP 810](https://peps.python.org/pep-0810/) before relying on any detail.

## Why imports are slow

Every `import` statement does real work the first time it runs: find the module, read and possibly compile it, execute its top level, and cache the result in `sys.modules`. Large libraries import many other modules in turn, so a single line like `import pandas` can account for a noticeable share of a script's startup.

The usual workaround has been to move the import inside the function that needs it:

```python
def export_report(rows):
    import csv  # deferred by hand
    ...
```

That works, but it scatters imports through the code, hides dependencies from readers and linters, and makes type annotations awkward. Lazy imports give you the same deferral while keeping the import at the top of the file.

## How the lazy keyword works

`lazy` is a soft keyword, so it does not break existing code that uses the word as a name. It prefixes an import statement:

```python
lazy import json
lazy from json import dumps

def handler(event):
    # json is actually imported here, on first use
    return dumps(event)
```

What happens, as described in the 3.15 documentation:

1. The statement binds the name immediately, but to a placeholder rather than the loaded module.
2. The first time you read that name, Python performs the real import and replaces the placeholder with the module (or attribute).
3. The placeholder type is exposed as `types.LazyImportType`.

If the function above is never called, `json` is never imported.

## What you cannot do

Lazy imports are deliberately limited:

- They are only allowed at module scope. Using `lazy` inside a function, a class body, or a `try`/`except`/`finally` block is a `SyntaxError`.
- Star imports (`from x import *`) cannot be lazy, and neither can `__future__` imports.

The `try` restriction matters because a common pattern is an optional dependency:

```python
try:
    import orjson
except ImportError:
    orjson = None
```

That pattern has to stay eager. A lazy import would not raise `ImportError` where the `try` block is, because nothing has been imported yet.

## Making existing code lazy without editing it

Two mechanisms exist for code you cannot or do not want to rewrite.

**`__lazy_modules__`.** A module can list fully qualified module names that should be imported lazily:

```python
__lazy_modules__ = ["json", "decimal"]

import json      # treated as lazy
import decimal   # treated as lazy
```

On Python versions before 3.15 the attribute is ignored and the imports stay eager. That makes it a reasonable way to write a library that supports older interpreters, because the same file runs correctly on both.

**A global switch.** The PEP describes a global lazy-imports flag with modes that include `all` (make imports lazy by default) and `normal` (the default, which only honours the `lazy` keyword). I could not confirm the exact command-line option and environment variable names from the sources available to me, so look them up in the documentation rather than copying them from this page. Treat `all` as a test tool first. Making every import lazy changes behaviour across your entire dependency tree, not just your own code.

## Where it helps

Lazy imports pay off when a large share of imported modules are not used on every run:

- **CLI tools with subcommands.** `mytool --help` should not import the database driver, the HTTP client and the plotting library.
- **Serverless and short-lived processes.** Startup is a visible part of each cold start.
- **Large applications with rarely used code paths**, such as admin tooling, report exports or optional integrations.
- **Test runs**, where collecting many files that import heavy libraries slows the loop.

It helps much less in a long-running web server that handles most routes within the first few seconds anyway. There the imports still happen, only later, and often on the first user request instead of at boot.

## Measure before you adopt it

Python already has a built-in way to see what costs time at startup:

```sh
python -X importtime -c "import myapp" 2> importtime.txt
```

The output lists the self and cumulative time for each module. Sort by cumulative time and look for a few heavy modules that are not needed on the hot path. Those are your candidates. If the list is flat, with no single expensive import, lazy imports will not change much.

Also compare before and after on the real entry point. A small script showing a gain does not tell you what your application's startup looks like. I would not quote a percentage from someone else's benchmark as a promise for your code.

## Pitfalls to check

**Import-time side effects move.** If a module registers a plugin, patches something or reads configuration when it is imported, deferring it changes when that happens, or whether it happens at all. Code that relied on `import plugin` for its side effect needs to stay eager.

**Errors surface later.** A missing dependency or a syntax error in a module is now raised at first use rather than at startup. A service can start cleanly and then fail on its first matching request. Keep a smoke test that touches every lazily imported module, or import them eagerly in a health-check path.

**First-call latency.** The cost does not disappear, it is paid by whoever triggers the import first. In a latency-sensitive API, that can be a real user. If that matters, warm the important modules on startup.

**Tooling support.** Linters, formatters, type checkers and IDEs need to understand the new syntax. At the time of my research there was an open request for isort to support it, so check your own toolchain on a branch before changing a shared codebase.

**Circular imports.** Lazy imports can hide an import cycle that would otherwise fail loudly, and the cycle may then appear only on one code path. Do not treat them as a fix for a cycle.

## A rollout approach

1. Run `python -X importtime` on your main entry points and list the slowest imports.
2. Convert only those, at the top of the module, with `lazy import`.
3. Leave optional-dependency `try` blocks and side-effect imports alone.
4. Run the full test suite, plus a test that exercises each lazily imported module.
5. Compare startup time on the real entry point before and after, and keep the change only if the difference is worth the added behaviour.
6. If you maintain a library that supports older Pythons, use `__lazy_modules__` rather than the keyword so the file still parses.

## Should you use it now?

Python 3.15 reportedly shipped in October 2026, though one secondary source gave the date and I could not confirm it against python.org. If your production environment is still on 3.13 or 3.14, the keyword is a `SyntaxError` there, so adoption in application code depends on your upgrade plan. Plan the move to 3.15 first, and keep the dependency-sensitive parts of the stack, such as C extensions and framework releases, in your compatibility check.

For a FastAPI or Django service, the realistic first step is a profile of import time, not a rewrite. If it shows a few heavy libraries that are only used in background jobs or admin screens, `lazy import` is a small, reviewable change. If you want help profiling a Python service's startup or planning a version upgrade, see my [Python, Django and FastAPI development](/services/python-fastapi-development/) services, or [tell me about your project](/contact/).

## Frequently asked questions

### Does `lazy import` make my program faster overall?

Not necessarily. It moves import cost from startup to first use. It saves time only for modules that are never used in a given run.

### Can I use it inside a function?

No. It is limited to module scope, and using it inside a function, class or `try` block is a `SyntaxError`.

### Will `__lazy_modules__` break older Python versions?

No. Before 3.15 the attribute is ignored and the imports run eagerly.

### Is it safe for optional dependencies?

Not with a `try`/`except ImportError` pattern, because the error would no longer occur where you catch it. Keep those imports eager.

## References and further reading

- [What's New in Python 3.15](https://docs.python.org/3.15/whatsnew/3.15.html)
- [PEP 810: Explicit lazy imports](https://peps.python.org/pep-0810/)
- [Explicit Lazy Imports Are Coming to Python 3.15, JetBrains PyCharm blog](https://blog.jetbrains.com/pycharm/2026/06/explicit-lazy-imports-are-coming-to-python-3-15/)
- [Python 3.15 release coverage, Linuxiac](https://linuxiac.com/python-3-15-released-with-faster-jit-lazy-imports-and-utf-8-by-default/)
- See also: [Django vs FastAPI](/blog/django-vs-fastapi/)

## Conclusion

Lazy imports are a startup-time tool, not a style choice. Use them where import cost is measurable and the module boundary is already clear; applying them everywhere makes the dependency graph harder to read for no gain.

Startup time is only one part of a Python upgrade, and [Django versus FastAPI](/blog/django-vs-fastapi/) covers the framework decision that usually comes with it. I do these upgrades under [Python and FastAPI development](/services/python-fastapi-development/). The change itself is documented in [Python's What's New page](https://docs.python.org/3/whatsnew/3.15.html). If your service takes seconds to start, [tell me what it imports](/contact/).

---

HTML version: https://fullstackweb.dev/blog/python-3-15-lazy-imports/
Maintained by Hendra Nicholas, Senior Full-Stack Software Engineer & AI Engineer, hello@fullstackweb.dev.
