In pydantic-settings, how do env_prefix and env_nested_delimiter decide which environment variable fills a nested database host field?
answer
- prefix glued to every name
- delimiter splits into nested keys
- sub-model is a BaseModel
- nested variable beats the JSON blob
basics
~10 senv_prefix is prepended to every variable name and env_nested_delimiter splits a name into nested keys, so with APP_ and __ the variable APP_DATABASE__HOST fills settings.database.host.
solid answer
~40 s`env_prefix` (default `''`) is glued to the front of each field's variable name, so `env_prefix="APP_"` turns `database` into `APP_DATABASE`. Without a delimiter, a sub-model field can only be set as JSON: `APP_DATABASE='{"host": "db.internal"}'`. Setting `env_nested_delimiter="__"` lets the library explode `APP_DATABASE__HOST=db.internal` into `{"database": {"host": "db.internal"}}`; several such variables merge, and a nested variable beats the same key inside the JSON variable. The sub-model should be a plain `BaseModel`, the delimiter only applies to names that point at declared fields, and matching ignores case by default. When the delimiter also appears inside field names, `env_nested_max_split` caps how deep a name is split. A field given `Field(validation_alias=...)` is read from the alias without the prefix, unless `env_prefix_target` says otherwise.
code
python · 23 linesimport os
from pydantic import BaseModel
from pydantic_settings import BaseSettings, SettingsConfigDict
class DatabaseSettings(BaseModel):
host: str = "localhost"
port: int = 5432
name: str
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="APP_", env_nested_delimiter="__")
debug: bool = False
database: DatabaseSettings
os.environ["APP_DATABASE"] = '{"host": "db.internal", "name": "orders"}'
os.environ["APP_DATABASE__PORT"] = "6432"
os.environ["APP_DATABASE__HOST"] = "replica.internal"
print(Settings().model_dump())
# {'debug': False, 'database': {'host': 'replica.internal', 'port': 6432, 'name': 'orders'}}go deeper
Remember that the prefix is glued to every name and that APP_DATABASE__HOST, with a double underscore delimiter, reaches settings.database.host.
Explain the explode-and-merge step, why nested variables beat the JSON blob, why the sub-model is a BaseModel, and how env_nested_max_split helps with a single underscore.
Diagnose a value that never arrives: check the delimiter count, the prefix, whether the name points at a declared field, and whether an alias skipped the prefix.
Set one naming convention across services, prefix plus double underscore, so operators can predict every variable name from the settings class without reading code.
## The problem the two options solve A real service has **nested configuration**: a database block with host, port and name, a cache block, a mail block. In pydantic-settings you model each block as a `BaseModel` and put it on the `BaseSettings` class as a field. Environment variables, though, are a **flat** list of strings. Two options in `SettingsConfigDict` bridge that gap: - **`env_prefix`** namespaces every variable the class reads, so two services, or two settings classes, can share one environment without colliding; - **`env_nested_delimiter`** tells the library which character sequence in a variable name means "go one level deeper". ## env_prefix: one string in front of every name `env_prefix` defaults to the empty string. When set, it is prepended to each field's variable name: | Field | `env_prefix=""` | `env_prefix="APP_"` | |---|---|---| | `debug` | `DEBUG` | `APP_DEBUG` | | `database` | `DATABASE` | `APP_DATABASE` | Points worth knowing: - matching ignores case by default (`case_sensitive=False`), and that applies to the prefix as well; - the prefix is not only for environment variables: it also applies to `.env` entries and to secret file names; - an alias does **not** get the prefix by default. `env_prefix_target` defaults to `"variable"`; set it to `"all"` to prefix aliases too, or `"alias"` to prefix only aliases. ## env_nested_delimiter: flat names into nested dicts Without a delimiter, the only way to set a sub-model from the environment is a **JSON string**, because complex fields are decoded as JSON: `APP_DATABASE='{"host": "db.internal", "name": "orders"}'`. With `env_nested_delimiter="__"`, the library also reads variables such as `APP_DATABASE__HOST` and **explodes** them: `APP_DATABASE__HOST=db.internal` becomes `{"database": {"host": "db.internal"}}`. Then: 1. variables with the same leading path are **merged**, so `APP_DATABASE__HOST` and `APP_DATABASE__PORT` build one dict; 2. a nested variable **takes precedence** over the same key in the top-level JSON variable, so `APP_DATABASE__PORT=6432` beats `"port": 5432` inside `APP_DATABASE`; 3. the delimiter only applies to variables that point at **declared fields**; a name that matches no field is not converted; 4. values are still strings, so `"6432"` is validated into an `int` by the sub-model's field. The documentation adds that the sub-model should inherit from `pydantic.BaseModel`. If it is itself a `BaseSettings`, the library initialises it separately and collects its fields on their own, which can give unexpected results. ## When the delimiter is a single underscore Many field names contain underscores. With `env_nested_delimiter="_"`, a name like `GENERATION_LLM_API_KEY` would be split at every underscore into `llm.api.key`. **`env_nested_max_split`** limits the number of splits: with `env_nested_max_split=1` the same variable becomes `llm.api_key`. The double underscore avoids the problem in most code bases, which is why it is the common choice. ## A worked example ```python import os from pydantic import BaseModel from pydantic_settings import BaseSettings, SettingsConfigDict class DatabaseSettings(BaseModel): host: str = "localhost" port: int = 5432 name: str class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix="APP_", env_nested_delimiter="__") debug: bool = False database: DatabaseSettings os.environ["APP_DATABASE"] = '{"host": "db.internal", "name": "orders"}' os.environ["APP_DATABASE__PORT"] = "6432" os.environ["APP_DATABASE__HOST"] = "replica.internal" print(Settings().model_dump()) # {'debug': False, 'database': {'host': 'replica.internal', 'port': 6432, 'name': 'orders'}} ``` The JSON variable supplies `name`, the nested variables override `host` and add `port`. ## Case and nesting Case-insensitive matching is the default, and the `case_sensitive` setting is applied to nested models as well. With `case_sensitive=True`, a JSON value such as `APP_DATABASE='{"HOST": "db.internal"}'` no longer fills a field called `host`, and validation reports `missing` for it. The documentation adds a platform caveat: on Windows, environment variable names reach Python already upper-cased, so `case_sensitive` has no effect for environment variables there, though `.env` entries keep their case. ## Debugging a nested value that never arrives 1. Print the expected name: prefix, field name, delimiter, nested field name, with nothing in between. 2. Check the delimiter is configured at all; without it, only the JSON form is read. 3. Check the field is declared on the model; undeclared paths are not exploded. 4. Check for an alias, which skips the prefix unless `env_prefix_target` is changed. ## Common mistakes - writing `APP_DATABASE_PORT` with one underscore when the delimiter is `__`: that name points at no declared field, so the port is never set; - forgetting the prefix on nested names: `DATABASE__PORT` is not read when `env_prefix="APP_"`; - doubling the delimiter after the prefix (`APP__DATABASE__PORT`): the prefix is glued straight to the field name; - expecting an aliased field to pick up the prefix automatically.
- Why should the nested database block be a BaseModel rather than another BaseSettings class?pydantic-settings documents that a sub-model must inherit from `pydantic.BaseModel`. A `BaseSettings` sub-model is initialised on its own and collects its fields separately from the environment, so the exploded nested variables may not land where you expect and the results can be surprising.
- A field has Field(validation_alias="DB_URL") and the class sets env_prefix="APP_"; which variable is read?`DB_URL`. `env_prefix_target` defaults to `"variable"`, which prefixes field names but not aliases. Set `env_prefix_target="all"` to read `APP_DB_URL` for the alias as well, or `"alias"` to prefix aliases only.
- Nested fields can only be set by putting the whole block in one JSON variable.
- With env_nested_delimiter set, the JSON variable overrides the individual nested variables.
- The delimiter goes between the prefix and the field name, as in APP__DATABASE.
- env_prefix applies only to environment variables, never to .env entries or secret files.
- An aliased field is read with the prefix added automatically.