Python Configuration Hierarchy — ELI5

When you get dressed on a cold morning, you layer up. First, you put on a t-shirt (the default). Then a sweater. Then a coat. Each layer overrides the one below it — the coat is what the world sees, but the t-shirt is still there underneath.

Python configuration works the same way — in layers.

Every app needs settings: What database should I connect to? How many retries should I attempt? Should I show debug messages? These settings need to change depending on where the app is running.

On your laptop, you might want debug mode on and a local database. On the production server, you want debug mode off and the real database. Same app, different settings.

Instead of changing the code every time, you stack settings in layers:

  1. Built-in defaults — the t-shirt. “Use port 8000. Retry 3 times. Debug mode off.”
  2. Config file — the sweater. A file that says “actually, use port 5000 and retry 5 times.”
  3. Environment variables — the coat. The server sets PORT=8080, which overrides everything below.
  4. Command-line flags — the hat. When you run the app, you type --debug and it overrides even the environment.

Each layer only needs to specify what’s different. The config file doesn’t repeat every default — just the ones it wants to change. The environment only sets what the server cares about.

If nothing at any layer says what port to use, the built-in default kicks in. If three layers all set the port, the highest layer wins.

One thing to remember: Configuration hierarchy means your app checks multiple sources for settings, and higher layers override lower ones — so defaults are always safe to fall back on.

pythonconfigurationproduction

See Also