---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Lazy settings and configuration

How does `LazySettings` stay unconfigured at import time, merge project values over defaults, and become an ordinary object on first attribute read?

Dozens of Django's own modules execute `from django.conf import settings` at top level — before `manage.py`, a WSGI entrypoint, or a standalone test script has set `"DJANGO_SETTINGS_MODULE"` or called `LazySettings.configure`. If importing `settings` read disk or inspected environment variables immediately, importing almost any part of Django would crash before user code got a chance to configure it.

## An inert `LazyObject` shell

At the bottom of `django/conf/__init__.py`, Django creates one module-level proxy: `settings = LazySettings()` (`django/conf/__init__.py:LazySettings`, `django/conf/__init__.py:settings`). `LazySettings` subclasses `LazyObject`, whose constructor does almost nothing except set a single attribute `LazyObject._wrapped` to a unique module-level sentinel named `empty` (`django/utils/functional.py:LazyObject`, `django/utils/functional.py:empty`).

> **History.** Look at line 269 of `django/utils/functional.py`: `LazyObject` declares `_wrapped = None` at class level with a comment referencing ticket `#19456`. Without that class attribute, attaching a Python profiler or trace hook during `LazyObject.__init__` caused `LazyObject.__getattribute__` to look up `_wrapped` before `__init__` had assigned it, triggering infinite recursion.

While `_wrapped` is still `empty`, importing `settings` touches zero files and reads zero environment variables. Even `LazySettings.__repr__` checks `self._wrapped is empty` first so debugging tools and tracebacks can print `<LazySettings [Unevaluated]>` without accidentally triggering configuration (`django/conf/__init__.py:LazySettings.__repr__`).

Only when code actually reads an attribute — `settings.DEBUG` in the trace below, or `settings.LOGGING_CONFIG` during `django.setup` — does Python fall through to `LazySettings.__getattr__`, which calls `LazySettings._setup` (`django/conf/__init__.py:LazySettings.__getattr__`, `django/conf/__init__.py:LazySettings._setup`).

```text recording=ch02-startup
LazySettings before and after first attribute read
  before read: repr(settings)=<LazySettings [Unevaluated]>  configured=False
  before read: 'DEBUG' in settings.__dict__ -> False
  LazySettings.__getattr__('DEBUG')
    LazySettings._setup(name='DEBUG')
      Settings.__init__('desk.settings')
  first read settings.DEBUG -> False; second read -> False (served from __dict__, __getattr__ skipped)
  after read: repr(settings)=<LazySettings "desk.settings">  configured=True
  after read: 'DEBUG' in settings.__dict__ -> True  global_defaults=150  explicit_settings=20
```

## Inside `Settings.__init__`

`LazySettings._setup` reads `os.environ.get("DJANGO_SETTINGS_MODULE")`. If that variable is unset or empty, it raises `ImproperlyConfigured` naming the exact setting requested. Otherwise it constructs `Settings(settings_module)` (`django/conf/__init__.py:Settings.__init__`) and binds it to `LazyObject._wrapped`.

`Settings.__init__` builds the merged configuration in a single linear pass. First it iterates `dir` over `django.conf.global_settings`, copying every attribute whose name satisfies `str.isupper` — all `150` built-in defaults in Django `6.1.3` (`django/conf/global_settings.py`). Next it calls `importlib.import_module` on the configured module name, overlays every uppercase attribute onto the `Settings` instance, and records each overridden name in `_explicit_settings` (`20` settings in our newsroom project). Lowercase helper variables and imported modules inside a settings file are silently ignored.

During that copy, Django immediately validates five list-or-tuple settings — `"ALLOWED_HOSTS"`, `"INSTALLED_APPS"`, `"TEMPLATE_DIRS"`, `"LOCALE_PATHS"`, and `"SECRET_KEY_FALLBACKS"` — raising `ImproperlyConfigured` if any of them was accidentally written as a bare string rather than a list or tuple. Without that check, writing `ALLOWED_HOSTS = "desk.example"` would iterate character by character and silently allow single-letter hostnames.

Finally, on POSIX systems that expose `"time.tzset"`, Django checks whether `TIME_ZONE` exists under `"/usr/share/zoneinfo"` (if that directory exists), copies `TIME_ZONE` into `os.environ["TZ"]`, and calls `"time.tzset()"` so C-level clock functions agree with Django's configured timezone.

> **History.** That `hasattr(time, "tzset")` guard carries a comment pointing to ticket `#2315`: early Django attempted to set process timezone state unconditionally, which broke on Windows where the C runtime has no `"tzset"` function and relies on different environment conventions.

> **Changed in 6.1.** Django 6.1 introduces `"MAILERS"` conflict checking and `RemovedInDjango2028Warning` deprecations inside `Settings.__init__` and `LazySettings.__getattr__` whenever legacy `EMAIL_*` settings are configured or read alongside `"MAILERS"` (`django/conf/__init__.py:_check_email_settings_conflicts`).

## The `__dict__` cache — and its hidden 14× tax

Back inside `LazySettings.__getattr__`, after fetching the value from `_wrapped`, Django applies two runtime adjustments: relative `"MEDIA_URL"` and `"STATIC_URL"` values get the active URL script prefix prepended via `LazySettings._add_script_prefix`, and an empty `"SECRET_KEY"` raises `ImproperlyConfigured`. Then line 145 executes a quiet optimization: `self.__dict__[name] = val`.

Because Python checks an instance's `__dict__` before calling `__getattr__`, the second read of `settings.DEBUG` in our trace never enters `LazySettings.__getattr__` at all. You might reasonably predict, then, that once `"DEBUG"` is cached in `__dict__`, reading `settings.DEBUG` costs the same as reading an attribute on any plain Python object — around `17 nanoseconds`.

Test that prediction across half a million reads on Python `3.14.8` and Django `6.1.3`, and the machine contradicts it:

```text recording=ch02-bench
LazySettings read cost (500,000 reads, median of 5 trials, nanoseconds per read)
  path                                  ns_per_read   relative
  plain object attribute                      17.0       1.0x
  settings.DEBUG (__dict__ cache hit)        236.4       13.9x
  LazySettings.__getattr__ (no cache)        599.8       35.3x
  self-caching speedup (__getattr__ / __dict__): 2.5x faster
```

```text figure=lazy-settings
LazySettings first-read promotion and measured attribute read cost (Django 6.1.3, 500,000 reads, median of 5 trials)

state promotion
  1. Import time: LazySettings(_wrapped=empty, configured=False, 'DEBUG' in __dict__=False)
  2. First read (settings.DEBUG): _setup -> Settings.__init__ (150 global_defaults + 20 explicit) -> __dict__['DEBUG'] = False
  3. Later reads: hits __dict__['DEBUG'] directly (skips __getattr__, still enters LazyObject.__getattribute__)
     Invalidation: override_settings swaps _wrapped -> LazySettings.__setattr__ calls __dict__.clear()

measured cost per attribute read (0 to 650 ns, to scale)
  Plain object (obj.DEBUG)                17.0 ns   1.0x  (CPython C-speed LOAD_ATTR)
  settings.DEBUG (__dict__ hit)          236.4 ns  13.9x  (LazyObject.__getattribute__ runs in Python every read)
  LazySettings.__getattr__ (uncached)    599.8 ns  35.3x  (full proxy + deprecation & URL checks; cache saves 2.5x)
```

*Caching resolved attributes into `__dict__` cuts lookup cost by `2.5x` (from `599.8 ns` to `236.4 ns`), yet a cached read on `settings` still costs nearly fourteen times a plain attribute read.*

Why does a `__dict__` cache hit on `settings` take `236.4 ns` instead of `17.0 ns`? The answer sits on `LazyObject.__getattribute__` (`django/utils/functional.py:LazyObject.__getattribute__`). Because `LazyObject` defines proxy dunder methods like `__eq__` and `__str__` that must delegate to the wrapped object rather than mask it, `LazyObject` overrides `__getattribute__` *in pure Python*. Every single `settings.DEBUG` lookup — cached or not — runs Python bytecode inside `__getattribute__`, checks `name == "_wrapped"`, calls `super().__getattribute__`, and calls `getattr(value, "_mask_wrapped", True)` before handing back `False`.

> **Deeper.** Two hundred nanoseconds is invisible in a view that executes once per request, which is why Django gladly accepts it in exchange for lazy configuration. Inside a tight loop that runs hundreds of thousands of times — template rendering, SQL compilation, or serialization — `236 ns` per iteration adds up, which is why Django's own hot loops copy `settings.DEBUG` into a local variable once before entering the loop.

## Standalone configuration with `configure`

Scripts and minimal tests that do not want a settings module on disk can call `LazySettings.configure` before the first attribute read (`django/conf/__init__.py:LazySettings.configure`). Instead of constructing `Settings`, `configure` wraps `django.conf.global_settings` inside a `UserSettingsHolder`, attaches every uppercase keyword option to it, and stores that holder in `LazyObject._wrapped` (`django/conf/__init__.py:UserSettingsHolder`). Calling `configure` after `LazySettings.configured` is already `True` raises `RuntimeError("Settings already configured.")` so two parts of a script cannot silently overwrite each other's boot config.

With configuration resolved — whether from a module or from `configure` — `django.setup` can finally build the app registry and import every app's models.
