Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Settings and Config

Settings Sources and .env Files

Control where Pydantic settings come from. Use env_prefix, aliases, nested delimiters, .env files, secrets directories and a custom order of sources.

In the previous lesson settings came from environment variables and class defaults. Real projects have more places to look: a .env file for local development, a directory of secret files in a container, and values passed directly in code, for example in a test. This lesson explains every source, the order Pydantic checks them in, and how to change that order.

Priority of sources

When the same setting appears in several places, the highest priority source wins. The default order, from strongest to weakest, is:

  1. Arguments passed to the constructor, Settings(port=1).
  2. Environment variables.
  3. A .env file (and other dotenv files you list).
  4. Files in a secrets directory.
  5. Default values in the class.
flowchart TB
    A["1. init arguments"] --> B["2. environment variables"]
    B --> C["3. .env file"]
    C --> D["4. secrets directory"]
    D --> E["5. class defaults"]

A source higher up hides the same key lower down.

Python Which source wins?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Prefixes and aliases

If many programs share a machine, a plain name such as PORT may collide with another program's variable. Set an env_prefix so that only MYAPP_PORT is read. You do that in model_config, using SettingsConfigDict, which is ConfigDict with the settings options added.

When one field must read a variable whose name differs from the field, give it a validation_alias. AliasChoices accepts several names and takes the first that is present.

Python env_prefix and AliasChoices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An alias is used as written, with no prefix added. That is useful for standard names such as DATABASE_URL or AWS_REGION that other tools also read.

Nested settings

Real configuration has groups: a database section, a cache section. Model them as nested models and tell Pydantic how to split variable names with env_nested_delimiter. With "__" (two underscores), DB__HOST fills db.host.

Python Nested models from flat variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can set a whole group at once as JSON (CACHE) or field by field (DB__HOST). Fields you do not set inside a group keep the group's own defaults, so db.name stays "app".

.env files

During development you do not want to export ten variables in every terminal. A dotenv file is a text file of NAME=value lines that the settings class reads for you. Point env_file at it:

Python
class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")

Real environment variables still beat the file, so production can override anything without editing it. The file is read relative to the current working directory, and a missing file is silently skipped. Never commit a .env that contains real secrets; commit a .env.example with placeholder values instead.

The editor here has a small in-memory file system, so the example can write its own .env and read it back. The package that parses dotenv files, python-dotenv, is installed together with pydantic-settings.

Python Reading a .env file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

env_file may also be a tuple, such as (".env", ".env.local"). Later files override earlier ones. The setting extra="ignore" matters here: by default a settings class forbids unknown keys in a dotenv file, because a typo like DEBGU=true should be noticed.

Secrets directories

Container platforms often mount each secret as a file: /run/secrets/db_password contains the password text. Set secrets_dir and a field named db_password reads that file. It is a good fit for Docker and Kubernetes secrets, and it ranks below the environment, so it works as a fallback. The file system here is writable, so you can try it:

Python A secrets directory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pydantic strips the trailing newline for you.

Changing the order of sources

The method settings_customise_sources returns the sources as a tuple, first = highest priority. Return them in a different order to change the rules, for example to make the .env file beat the environment, or to drop a source entirely.

Python A custom source order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can also write your own source, for instance one that reads a JSON or YAML file, by returning any callable that produces a dictionary. pydantic-settings ships ready-made sources for JSON, TOML and YAML files too.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A variable PORT=6000 is set and the .env file says PORT=5000. Which value does the default settings class use?

    The default priority is init arguments, then environment, then dotenv, then secrets files, then defaults.
  2. 2. What does env_nested_delimiter="__" allow?

    The delimiter splits a variable name into a path, so DB__HOST sets db.host.
  3. 3. How do you read a variable called DATABASE_URL into a field named db when env_prefix is MYAPP_?

    An alias names the variable exactly, so the prefix is not added in front of it.
  4. 4. Why does a settings class raise an error for an unknown key in a .env file by default?

    Set extra="ignore" if the file holds variables for other programs as well.

Summary

  • Sources in default priority: init arguments, environment, .env, secrets directory, defaults.
  • env_prefix namespaces variables; a validation_alias is used exactly as written.
  • env_nested_delimiter maps DB__HOST onto nested models, and a whole group can be one JSON variable.
  • env_file loads dotenv files; keep real secrets out of version control.
  • settings_customise_sources reorders, removes or adds sources.

Next: ConfigDict Options