Speeding Up Django Startup Times with Lazy Imports

Anže Pečar
DjangoCon Europe 2026

Imports in Python can be slow

python -X importtime ./manage.py check
  Slowest imports by self time (all levels):

     self  cumulative  package
  ───────────────────────────────────────────────────────────────────────────────────
  783.5ms       2.30s  google.cloud.asset_v1
  965.7ms     978.9ms  google.pubsub_v1
  720.1ms     767.2ms  google.cloud.osconfig_v1
  709.9ms     710.4ms  google.api_core
  661.7ms     725.0ms  google.cloud.orgpolicy_v2
  332.8ms     498.5ms  google.cloud.monitoring_v3
  144.8ms     146.1ms  google.cloud.monitoring_v3.services.group_service.async_client
  129.5ms     129.5ms  snowflake.core.network_policy._generated.models.tag_reference
  115.2ms     115.2ms  apps.integrations.gcp.datastructures

Eager imports

from google.cloud.storage import Client as StorageClient

def get_storage_client() -> StorageClient:
    return StorageClient(...)

Lazy imports

if TYPE_CHECKING:
    from google.cloud.storage import Client as StorageClient

def get_storage_client() -> StorageClient:
    from google.cloud.storage import Client as StorageClient
    return StorageClient(...)

Lazy imports

def get_storage_client_1():
    from google.cloud.storage import Client as StorageClient
    return StorageClient(...)

def get_storage_client_2():
    from google.cloud.storage import Client as StorageClient
    return StorageClient(...)

def get_storage_client_3():
    from google.cloud.storage import Client as StorageClient
    return StorageClient(...)

From 13s to 3s

MetricValue
Files changed130
Lines added1,125
Lines deleted547
Net lines added578

Problem 1: Make sure not to regress

[tool.ruff.flake8-tidy-imports]
banned-module-level-imports = [
  "snowflake",
  "google",
  "googleapiclient",
  ...
]

Problem 2: Loading imports during request/response

Pre-load the heavy imports before your web worker starts (e.g. post_worker_init if using gunicorn).

PEP 810: Explicit Lazy Imports (Python 3.15) 😍

Explicit lazy imports

lazy from google.cloud.storage import Client as StorageClient

def get_storage_client() -> StorageClient:
    return StorageClient(...)

Implicit lazy imports

python -X lazy_imports=all
from google.cloud.storage import Client as StorageClient

def get_storage_client() -> StorageClient:
    return StorageClient(...)

🤫 Lazy imports allow circular imports

# a.py
lazy from .b import B

class A:
    def get_b(self):
        return B(self)
# b.py
lazy from .a import A

class B:
    def get_a(self):
        return A(self)

✅ This now imports without errors

Be lazy!