Lazy Imports in Python: Benefits, Examples and Best Practices

How to load a module only when your code actually needs it, what that buys you in startup time, what it costs you in predictability, and where the new lazy import syntax in Python 3.15 fits.

Lazy Imports in Python cover: a code window comparing an eager pandas import, a function-local import and the Python 3.15 lazy import keyword, with measured startup times of 246 ms eager and 19 ms lazy

Introduction

Every import at the top of a Python file runs when that file loads. That is fine until top-level imports pull in heavy libraries that only one code path uses. Then you get a CLI that takes a quarter of a second to print --version, or a Django project where every management command, test run and worker boot pays for a PDF library one admin view needs.

Lazy imports in Python fix this by loading a module when the code first needs it, not when the program starts. Code paths that never use the module never pay for it. Paths that do use it pay the same cost, just later. Lazy imports move cost; they do not remove it.

This guide covers how imports work, six ways to defer them, a measured before-and-after benchmark, Django guidance and the trade-offs. Examples were tested on Python 3.12, and the lazy keyword examples on a Python 3.15 pre-release.

What Are Lazy Imports in Python?

A regular import runs as soon as Python reaches the statement. Here pandas, and NumPy with it, loads whether or not anyone calls analyze_data():

import pandas as pd


def analyze_data(data):
    return pd.DataFrame(data)

The simplest lazy import moves the statement into the function:

def analyze_data(data):
    import pandas as pd

    return pd.DataFrame(data)

pandas now loads on the first call. Later calls find it in Python's module cache and skip the expensive part.

Strictly, this defers the import. It is not a lazy module object. LazyLoader, lazy_loader and Python 3.15's lazy import create a placeholder that loads on first attribute access, which is a different mechanism. Either way, only the cost of importing (running the module's top-level code) moves. The work your code does afterwards is unchanged.

How Python Imports Work

When Python executes import pandas, the import system roughly does this:

  1. Check the cache. If "pandas" is already in sys.modules, bind it and stop.
  2. Find the module on sys.path.
  3. Create and register it in sys.modules before its code runs, which is what makes circular imports partially work.
  4. Execute it. Run the module's top-level code, reusing cached bytecode from __pycache__ when possible.

Execution is the expensive step, and it is recursive: every import inside pandas repeats the process. One line in your file can initialise hundreds of modules. Import-time side effects, such as reading config, compiling regexes or building lookup tables, add to the bill in every process.

Most imports are cheap. Do not move every import into functions. Measure first and target the few that matter.

Measure import cost with -X importtime

CPython's built-in import profiler, -X importtime (since 3.7), prints each import's time in microseconds to stderr:

python -X importtime -c "import pandas" 2> import.log
sort -t'|' -k2 -n import.log | tail -5
import time:  self [us] | cumulative | imported package
import time:      1073 |      41022 |       pandas.core.groupby.generic
import time:       948 |      58594 |   numpy
import time:       206 |      71552 |   pandas.core.api
import time:       284 |     199819 | pandas

On my machine, import pandas took about 200 ms cumulative, with NumPy near 59 ms. self is time in a module's own top-level code; cumulative includes everything it imported. Sort by cumulative to find the expensive roots. Python 3.14's -X importtime=2 also reports cache hits, which helps answer "who else imports this?"

Different Ways to Implement Lazy Imports

Start with the simplest approach that solves your problem.

Approach A: import inside a function

def generate_report(data):
    import pandas as pd

    frame = pd.DataFrame(data)
    return frame.describe()

No tools, no indirection, and the dependency sits next to the code that needs it. The first call pays the import; later calls do a sys.modules lookup. I measured about 80 ns per call against 24 ns for a module-level name: negligible for a report, worth avoiding in a loop that runs millions of times. Use it for heavy dependencies that one or two functions need.

Approach B: import inside a conditional branch

def export_data(rows, fmt):
    if fmt == "csv":
        import pandas as pd

        return pd.DataFrame(rows).to_csv(index=False)

    if fmt == "json":
        import json

        return json.dumps(rows)

    raise ValueError(f"Unsupported format: {fmt}")

Each branch loads only what it needs, so a JSON caller never loads pandas. This matters most for optional dependencies: users without pandas can still export JSON. (import json is inside the branch only for symmetry; it is cheap enough for the top of the file.)

Approach C: import on demand with importlib

When the module name is data, such as a backend chosen in settings, use importlib.import_module(). This is the basis of most plugin systems:

import importlib

EXPORTERS = {
    "csv": "myapp.exporters.csv_exporter",
    "xlsx": "myapp.exporters.xlsx_exporter",
}


def load_exporter(name):
    try:
        module_path = EXPORTERS[name]
    except KeyError:
        raise ValueError(f"Unsupported exporter: {name!r}") from None

    return importlib.import_module(module_path)

Approach D: module-level __getattr__ (PEP 562)

Since Python 3.7, PEP 562 lets a module define __getattr__, which runs only when normal attribute lookup fails. A package can use it to import submodules on first access:

# analytics/__init__.py
import importlib

_LAZY_SUBMODULES = {"charts", "forecasting"}


def __getattr__(name):
    if name in _LAZY_SUBMODULES:
        return importlib.import_module(f".{name}", __name__)
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


def __dir__():
    return sorted(set(globals()) | _LAZY_SUBMODULES)

import analytics stays cheap, and analytics.charts loads on first use. After that the import system has set charts on the package, so __getattr__ is not called again. __dir__ keeps the lazy names visible in dir() and completion.

The cost is discoverability: IDEs and type checkers cannot see these attributes without a .pyi stub or TYPE_CHECKING imports. Use it for libraries with a large public namespace, not application code.

Approach E: lazy module objects (stdlib and third-party)

To get a module object at the top of the file that loads only when used, before Python 3.15:

  • Standard library: importlib.util.LazyLoader (Python 3.5+), with a short recipe in the docs. The docs discourage it unless startup time is critical, because load errors surface later and out of context.
  • Third party: lazy_loader from Scientific Python, used by scikit-image. It provides lazy_loader.load("numpy") and lazy_loader.attach() to generate a package's __getattr__. At the time of writing it is actively maintained (version 0.6, September 2026, Python 3.9+), but it is another dependency to track.

Both trade simple code for a proxy that is harder to debug. For application code, function-local imports give the same benefit without the machinery.

Approach F: interpreter-level lazy imports (Python 3.15+)

PEP 690, which proposed making all imports lazy behind a global flag, was rejected. PEP 810, Explicit lazy imports, lets the developer mark individual imports instead. It is Final and ships in Python 3.15, whose final release was scheduled for 9 October 2026 (PEP 790). Check What's New in Python 3.15 for the release you install.

# Python 3.15+ only
lazy import json
lazy from pathlib import Path

print("Starting up...")       # json and pathlib are not loaded yet

data = json.loads('{"a": 1}')  # json loads here, on first use
here = Path(".")               # pathlib loads here

What I verified on a 3.15 pre-release, and what the documentation states:

  • lazy is a soft keyword, so existing variables named lazy keep working.
  • The statement binds a placeholder. The real import happens on first use, and Python replaces the placeholder (the PEP calls this reification).
  • Lazy imports are only allowed at module level. Inside a function, class body or try/except, they are a SyntaxError. Star imports and from __future__ imports cannot be lazy.
  • A missing module raises ImportError at first use, with the original ModuleNotFoundError chained.
  • -X lazy_imports=all or PYTHON_LAZY_IMPORTS=all makes module-level imports lazy without the keyword; normal (the default) respects only explicit ones. sys.set_lazy_imports() and sys.set_lazy_imports_filter() control this at runtime and are meant for applications, not libraries.

Python 3.14 and earlier cannot parse lazy. For code that must support both, PEP 810 adds a module-level __lazy_modules__ list, which 3.15 honours and older versions ignore. I confirmed both behaviours on 3.12 and the 3.15 pre-release:

__lazy_modules__ = ["pandas"]

import argparse
import pandas as pd   # lazy on Python 3.15+, an ordinary import on older versions

Benefits of Lazy Imports

Every benefit comes from one fact: code that never runs an import never pays for it. That also sets each benefit's limit.

  • Faster startup for short-lived processes: CLIs, scripts, serverless functions, test runs and autoscaled workers. No gain if most runs use the module anyway.
  • Smaller import trees. Deferring one root defers hundreds of transitive modules. If another module imports it eagerly, it still loads at startup, so confirm with -X importtime.
  • Optional dependencies. With extras such as pip install mytool[excel], a missing package fails only on its own path. You need a clear error message and tests for both cases.
  • Responsive CLIs. --help, --version and shell completion stop paying for every subcommand's dependencies.
  • Lower initial memory. In the benchmark below, the eager CLI peaked at about 65 MiB for version and the lazy one at about 11 MiB. Once the module loads, memory is the same. Pre-forking servers such as Gunicorn with --preload can even lose: modules loaded before the fork share pages across workers through copy-on-write, while a lazy module loads separately in each worker.
  • Plugin architectures. Only the configured backend loads. A broken backend is found only when selected, so import every registered backend in a test.

Before-and-After Example: A Report CLI

A small CLI with two subcommands: version prints a string, summary reads a CSV with pandas. Install pandas first (pip install pandas in a virtual environment).

Eager version

# report_eager.py
import argparse

import pandas as pd


def show_version(args):
    print("report-cli 1.0.0")


def summarize(args):
    frame = pd.read_csv(args.path)
    print(frame.describe())


def main():
    parser = argparse.ArgumentParser(prog="report-cli")
    commands = parser.add_subparsers(required=True)

    version = commands.add_parser("version")
    version.set_defaults(handler=show_version)

    summary = commands.add_parser("summary")
    summary.add_argument("path")
    summary.set_defaults(handler=summarize)

    args = parser.parse_args()
    args.handler(args)


if __name__ == "__main__":
    main()

Running version imports argparse, then pandas and NumPy, then parses arguments and prints one line.

Lazy version

The only change is where pandas is imported:

# report_lazy.py (only the changed parts)
import argparse


def summarize(args):
    import pandas as pd

    frame = pd.read_csv(args.path)
    print(frame.describe())

Now version goes straight from parsing to printing. On Python 3.15+, lazy import pandas as pd at the top gives the same effect without moving the line. I checked that flow on a 3.15 pre-release with a stand-in module, because pandas did not yet run on that build.

Benchmark script

The script runs each command as a fresh process. The import cache lives inside a process, so timing imports in one long-running process would measure the cache, not startup.

# bench.py
import statistics
import subprocess
import sys
import time

RUNS = 20


def measure(command):
    timings = []
    for _ in range(RUNS):
        start = time.perf_counter()
        subprocess.run(command, check=True, stdout=subprocess.DEVNULL)
        timings.append(time.perf_counter() - start)
    return statistics.median(timings) * 1000


def main():
    python = sys.executable
    cases = {
        "baseline (python -c pass)": [python, "-c", "pass"],
        "eager version": [python, "report_eager.py", "version"],
        "lazy version": [python, "report_lazy.py", "version"],
        "eager summary": [python, "report_eager.py", "summary", "sales.csv"],
        "lazy summary": [python, "report_lazy.py", "summary", "sales.csv"],
    }
    # One warm-up run per case so the OS file cache is not part of the result
    for command in cases.values():
        subprocess.run(command, check=True, stdout=subprocess.DEVNULL)

    print(f"Python {sys.version.split()[0]}, {RUNS} runs each, median wall time")
    for label, command in cases.items():
        print(f"{label:<28} {measure(command):8.1f} ms")


if __name__ == "__main__":
    main()

Put bench.py, both CLI files and a small sales.csv with a few numeric columns in one folder and run python bench.py.

Measured results

Real numbers from one machine: Linux, Intel Core i5-1155G7, Python 3.12.3, pandas 3.0.6, median of 20 runs. Two runs matched within about 15 ms.

CommandEagerLazy
python -c pass (interpreter baseline)11 ms11 ms
version246 to 259 ms19 ms
summary sales.csv262 to 272 ms262 to 265 ms
  • version got about 13 times faster, because it no longer loads pandas.
  • summary did not change. It still pays roughly 250 ms for pandas, at a different line.

Your numbers will vary with hardware, versions and cache state, so run the script on your own tool. The pattern holds: lazy imports speed up paths that skip the module and do nothing for paths that use it.

Lazy Imports in Django Applications

Django loads a lot at startup on purpose. django.setup() imports every app in INSTALLED_APPS, their models and AppConfig.ready() hooks. Middleware loads when the WSGI or ASGI handler is created, and the URLconf with every views module it references loads on first URL resolution or during system checks. Anything those modules import at the top level loads in every web worker, Celery worker, test run and manage.py command.

Good candidates for deferral: heavy libraries in management commands, Excel, PDF or Parquet exports, Pillow or OpenCV on a single upload path, single-integration SDKs, and rarely used admin actions.

A rarely used export view

# orders/views.py
import io

from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse

from .models import Order

XLSX_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"


@staff_member_required
def export_orders_xlsx(request):
    # openpyxl is only needed by this rarely used admin export
    from openpyxl import Workbook

    workbook = Workbook()
    sheet = workbook.active
    sheet.append(["ID", "Status", "Total"])
    for row in Order.objects.values_list("id", "status", "total").iterator():
        sheet.append(list(row))

    buffer = io.BytesIO()
    workbook.save(buffer)

    response = HttpResponse(buffer.getvalue(), content_type=XLSX_TYPE)
    response["Content-Disposition"] = 'attachment; filename="orders.xlsx"'
    return response

Every other view in the file, and every worker that imports it, no longer loads openpyxl.

A management command with an optional dependency

Django imports a command's module only when you run that command, so top-level imports in a command file only slow that command. The pattern below helps when one command has an optional, heavier mode:

# orders/management/commands/export_orders.py
from django.core.management.base import BaseCommand, CommandError

from orders.models import Order


class Command(BaseCommand):
    help = "Export orders as CSV or Parquet."

    def add_arguments(self, parser):
        parser.add_argument("path")
        parser.add_argument("--format", choices=["csv", "parquet"], default="csv")

    def handle(self, *args, **options):
        rows = Order.objects.values("id", "status", "total")

        if options["format"] == "parquet":
            try:
                import pandas as pd
                import pyarrow  # noqa: F401  pandas uses it to write Parquet
            except ImportError:
                raise CommandError(
                    "Parquet export needs pandas and pyarrow: pip install pandas pyarrow"
                ) from None
            pd.DataFrame.from_records(rows).to_parquet(options["path"])
        else:
            import csv

            with open(options["path"], "w", newline="") as handle:
                writer = csv.DictWriter(handle, fieldnames=["id", "status", "total"])
                writer.writeheader()
                writer.writerows(rows)

        self.stdout.write(self.style.SUCCESS(f"Exported to {options['path']}"))

The import pyarrow line is deliberate. My first version only checked for pandas; with pyarrow missing, the command failed deep inside to_parquet() with a less helpful error. Check every dependency the deferred path needs, up front.

Django-specific cautions

  • Import-time side effects. Some imports register signal receivers, admin classes, template tags, checks or serializers. Deferring them changes behaviour, not just timing. If signals.py is only imported from a lazy path, receivers silently do nothing until that path runs.
  • AppConfig.ready(). Django recommends importing signal handlers inside ready(). That import is deferred but required at startup; keep it there (see below).
  • Model discovery. Django finds models by importing each app's models module during setup. Never hide models behind a lazy path.
  • Circular imports. A function-local import can break a cycle between apps, but treat it as a patch. Fix the dependency direction, or refer to models by string ("orders.Order") and apps.get_model().
  • Tests. An earlier test may already have cached a deferred import, so the first-use path behaves differently in a full suite. Use unittest.mock.patch.dict(sys.modules, ...) to test the missing-package case.
  • Optional dependencies. Document which features need which extras, and raise CommandError or ImproperlyConfigured instead of a raw ImportError.
# orders/apps.py
from django.apps import AppConfig


class OrdersConfig(AppConfig):
    name = "orders"

    def ready(self):
        # Registers signal receivers. This must run at startup, so it is
        # not a candidate for lazy loading.
        from . import signals  # noqa: F401

I ran these examples in a minimal Django 6.1 project. The signal fired, the CSV export worked, the Parquet path raised CommandError when pyarrow was missing, and openpyxl was not in sys.modules until the export view ran.

In most Django projects import time is not the bottleneck. Lazy imports do not replace query optimization, indexing, caching, or keeping heavy work out of app initialization and the request cycle. If pages are slow, look at the queries first; my post on scaling Django applications to millions of records covers that side.

Potential Drawbacks and Limitations

  • Delayed errors. A missing dependency used to fail at startup, where deploy checks catch it. Now it fails when a user clicks Export. Mitigation: a CI and deploy smoke test that imports every optional dependency expected in that environment.
  • First-use latency. The first request that needs the module pays the whole import, about 250 ms in the benchmark. Mitigation: in long-running servers that use the module regularly, import it at startup or warm it up after boot.
  • Harder debugging. With proxy-based approaches, errors surface at an attribute access far from the import. Mitigation: prefer plain function-local imports.
  • Hidden circular imports. A local import stops the error without removing the cycle. Mitigation: comment it as a short-term fix, then move shared code to a third module or reverse one dependency.
  • Untested paths. A suite that never calls the export function never imports its dependency. Mitigation: test every lazy path, plus the "dependency missing" case for optional ones.
  • Maintenance cost. A home-grown framework of proxies and import hooks can cost more engineering time than it saves. Mitigation: start with function-local imports; on 3.15+, prefer the standard lazy keyword.

Type checking and IDE support

Type checkers handle function-local imports well, but importlib calls and __getattr__ are opaque to them, and a local import leaves no module-level name for annotations. Import types under TYPE_CHECKING: type checkers see them; the runtime does not execute them.

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import pandas as pd


def load_sales(path: str) -> pd.DataFrame:
    import pandas as pd

    return pd.read_csv(path)

Threading and concurrency

Python's import system uses per-module locks, so plain function-local imports are thread-safe. Custom first-use logic is not. If you build an expensive client or parsed config on first use, two threads can both see "not built yet" and both build it. Guard it with a lock:

import threading

_client = None
_client_lock = threading.Lock()


def get_client():
    global _client
    if _client is None:
        with _client_lock:
            if _client is None:
                from storage_sdk import Client  # placeholder for a heavy SDK

                _client = Client.from_env()
    return _client

When Should You Use Lazy Imports?

When to use lazy imports, by scenario
ScenarioRecommended approachReasonImportant consideration
Rarely used heavy dependencyFunction-local importMost runs never need itTest the path; expect first-use latency
Optional export or integrationImport inside the branch, with a clear errorUsers without the extra can use everything elseDocument the extra; test installed and missing cases
Small command-line utilityFunction-local imports per subcommand, or lazy import on 3.15+Startup time is most of the run timeMeasure with -X importtime and a subprocess benchmark
Core application initializationRegular top-level importsSettings, models and app registry must load predictablyDeferring them can break behaviour
Frequently used request handlersRegular top-level importsThe module loads anyway; laziness only moves the cost into a requestWarm up at boot rather than on the first request
Plugin or backend systemimportlib.import_module() with an allowlistOnly the selected plugin loadsNever pass untrusted input; import all plugins in tests
Modules with required import-time side effectsRegular imports, or Django's AppConfig.ready()Signals, registries and checks must run at startupLazy loading here causes silent failures
Library with a large public namespaceModule __getattr__ (PEP 562) or lazy_loaderimport yourlib stays cheap for every userAdd stubs or TYPE_CHECKING imports for IDEs

Top-level imports remain the right default. They make dependencies visible, fail fast and match what linters and other developers expect. Defer an import when a measurement shows it pays off, follow one convention per project, and comment why each import is deferred.

Conclusion

Lazy imports move the cost of loading a module from program start to first use. When a code path never needs the module, the cost disappears: the version command above dropped from about 250 ms to 19 ms. When it does need the module, nothing changes except when you pay. A function-local import is usually all you need; importlib serves plugin systems, PEP 562 serves large libraries, and Python 3.15's lazy import lets you keep imports at the top of the file and still defer them.

Frequently Asked Questions

What is a lazy import in Python?

An import that loads a module when the code first needs it instead of at program start. The common form is an import inside the function that uses the module. Python 3.15 adds an explicit lazy import statement.

Do lazy imports improve Python performance?

They improve startup time and initial memory for code paths that never use the deferred module. They do not make the module faster or help paths that use it on every run.

Are imports inside Python functions bad practice?

Not when they have a reason. PEP 8's top-level default is right for most code. A function-local import is reasonable for heavy optional dependencies, as a temporary fix for a circular import, or in Django's AppConfig.ready(). Add a short comment saying why.

Can lazy imports reduce memory usage?

For processes that never use the deferred module, yes. In the benchmark, version peaked at about 11 MiB instead of 65 MiB. Once the module is imported, memory is the same as with an eager import.

Are lazy imports useful in Django?

Yes, for heavy dependencies used by a few views, admin actions or management commands. Keep models, signal registration and app initialization as regular imports. Query performance usually matters far more than import time.

How can I measure Python import time?

Use python -X importtime (or PYTHONPROFILEIMPORTTIME) for per-module times. To measure what users feel, time complete process runs with subprocess and time.perf_counter(), as in the benchmark script above.

Is lazy importing built into Python?

Partly, and more so from 3.15. importlib.util.LazyLoader exists since 3.5 and module-level __getattr__ since 3.7. Python 3.15 adds lazy import and lazy from ... import from PEP 810; on 3.14 and earlier that syntax is a SyntaxError.

References