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 at top level — before manage.py, a WSGI entrypoint, or a standalone test script has set "DJANGO_SETTINGS_MODULE" or called LazySettings. 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/, Django creates one module-level proxy: settings = LazySettings(). LazySettings subclasses LazyObject, whose constructor does almost nothing except set a single attribute LazyObject to a unique module-level sentinel named empty.
While _wrapped is still empty, importing settings touches zero files and reads zero environment variables. Even LazySettings checks self first so debugging tools and tracebacks can print <LazySettings [Unevaluated]> without accidentally triggering configuration.
Only when code actually reads an attribute — settings.DEBUG in the trace below, or settings during django.setup — does Python fall through to LazySettings, which calls LazySettings.
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 reads os. If that variable is unset or empty, it raises ImproperlyConfigured naming the exact setting requested. Otherwise it constructs Settings(settings_module) and binds it to LazyObject.
Settings builds the merged configuration in a single linear pass. First it iterates dir over django, copying every attribute whose name satisfies str.isupper — all 150 built-in defaults in Django 6.1.3. Next it calls importlib 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 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 "/ (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.
The __dict__ cache — and its hidden 14× tax
Back inside LazySettings, 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, and an empty "SECRET_KEY" raises ImproperlyConfigured. Then line 145 executes a quiet optimization: self.
Because Python checks an instance’s __dict__ before calling __getattr__, the second read of settings.DEBUG in our trace never enters LazySettings 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:
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
__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. 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.
Standalone configuration with configure
Scripts and minimal tests that do not want a settings module on disk can call LazySettings before the first attribute read. Instead of constructing Settings, configure wraps django inside a UserSettingsHolder, attaches every uppercase keyword option to it, and stores that holder in LazyObject. Calling configure after LazySettings 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.