skip to content

In pydantic-settings, why does an unknown line in the .env file stop startup with extra_forbidden, while an unknown environment variable is ignored?

level: seniorimportance: should knowfreq 38%

answer

  1. two sources read differently
  2. dotenv hands over every entry
  3. BaseSettings default for extra
  4. filtering or ignore fixes it

basics

~20 s

The environment source looks up only declared fields' names, but the dotenv source passes .env entries no field uses into the model as input, and BaseSettings defaults to extra='forbid', so an undeclared entry fails validation.

solid answer

~40 s

The two sources work differently. `EnvSettingsSource` asks the environment only for the names of declared fields, so unrelated variables are never seen. `DotEnvSettingsSource` reads the whole file and, by default, passes every entry that is not used by a field into the model as input. `BaseSettings` sets `extra="forbid"` (plain `BaseModel` uses `"ignore"`), so an undeclared entry fails with `extra_forbidden`, "Extra inputs are not permitted", located at the entry's name. The documentation says to use `extra="ignore"` for version 1 `BaseSettings` behaviour. Narrower fixes keep the strictness: `dotenv_filtering="match_prefix"` passes only entries starting with the class's `env_prefix`, and `"only_existing"` passes only entries that map to fields. With an `env_prefix`, an unprefixed entry that matches a field name is silently skipped.

code

ini · 4 lines
ini
# .env
APP_DEBUG=true
APP_DATABASE__NAME=orders
REPORTING_TOKEN=abc123

go deeper

for a junior

Know that BaseSettings rejects unknown .env entries by default and that the error type is extra_forbidden.

for a middle

Explain why the environment source never sees unrelated variables while the dotenv source passes every entry, and how extra and dotenv_filtering change that.

for a senior

Pick the narrowest fix: match_prefix for a shared file keeps typo detection, extra='ignore' trades it away; mention the unprefixed-entry asymmetry and that version 1 tolerated clutter.

for a principal

Set a convention for .env files across services, one file per service or a prefix per service with match_prefix, so strict validation stays on without breaking local development.

## The symptom A service starts fine in production, where its configuration comes from environment variables. A developer adds `REPORTING_TOKEN=...` to the shared `.env` file for a different tool, and now the service refuses to start locally: ```python exc.errors(include_url=False) # [{'type': 'extra_forbidden', 'loc': ('reporting_token',), # 'msg': 'Extra inputs are not permitted', 'input': 'abc123'}] ``` The same variable exported in the shell would have been ignored. The difference is not in the values but in **how each source reads**. ## Two sources, two reading strategies | | Environment source | Dotenv source | |---|---|---| | class | `EnvSettingsSource` | `DotEnvSettingsSource` | | what it reads | the variable names of declared fields | every entry in the file | | unused entries | never collected | passed to the model as input (empty values are skipped) | | unknown name | invisible | becomes an extra key | `EnvSettingsSource` starts from the **model**: for each field it works out the variable name (prefix, field name or alias, delimiter) and looks only for that. A process environment holds dozens of unrelated variables, such as `PATH` and `HOME`, and none of them is ever considered. `DotEnvSettingsSource` starts from the **file**. It loads every entry, uses the ones that belong to declared fields, and, unless told otherwise, adds the rest to the input dictionary. The file is treated as "configuration for this class", so an entry nobody declared looks like a mistake. ## Why it becomes an error `BaseSettings` sets `extra="forbid"` in its default `model_config`, where a plain `BaseModel` defaults to `extra="ignore"`. With `forbid`, any undeclared key in the input fails validation with error type **`extra_forbidden`**. The location is the entry's name as read from the file, lower-cased when matching is case-insensitive, and the message prints the value, which is one more reason to set `hide_input_in_errors=True` if the file holds secrets. This is a **version change** worth knowing during a migration. The pydantic-settings documentation says that for compatibility with version 1's `BaseSettings` you should set `extra="ignore"`: a version 1 service that tolerated a cluttered `.env` file can start failing after the move. ## The fixes, from broadest to narrowest 1. **`extra="ignore"`**: undeclared entries are dropped for every input source. Simple, but it also hides typos such as `APP_DEBGU=true`. 2. **`dotenv_filtering="match_prefix"`**: only entries starting with the class's `env_prefix` are passed, with the prefix stripped. This scopes one shared file to one settings class, and a typo inside your own prefix still fails. 3. **`dotenv_filtering="only_existing"`**: only entries that map to declared fields are passed, so the dotenv source behaves like the environment source. 4. **Separate files per service**: `env_file` can name a service-specific file, or a tuple where later files override earlier ones. ## The prefix asymmetry With `env_prefix="APP_"` and a field `debug`, the documentation describes a surprising exception: an **unprefixed** `.env` line `debug=true` is silently skipped. It neither sets the field (only `APP_DEBUG` does) nor raises `extra_forbidden`. A non-matching unprefixed line such as `foo=1` still raises. So a developer who forgets the prefix gets no error and no value. ## A worked example ```ini # .env APP_DEBUG=true APP_DATABASE__NAME=orders REPORTING_TOKEN=abc123 ``` ```python from pydantic import BaseModel, ValidationError from pydantic_settings import BaseSettings, SettingsConfigDict class DatabaseSettings(BaseModel): host: str = "localhost" name: str class Settings(BaseSettings): model_config = SettingsConfigDict( env_prefix="APP_", env_nested_delimiter="__", env_file=".env" ) debug: bool = False database: DatabaseSettings try: Settings() except ValidationError as exc: print(exc.errors()[0]["type"], exc.errors()[0]["loc"]) # extra_forbidden ('reporting_token',) ``` Adding `dotenv_filtering="match_prefix"` to the config makes the same file load cleanly, because `REPORTING_TOKEN` does not start with `APP_`. ## A missing file is not an error The dotenv source skips a file that does not exist, so a production image without a `.env` file loads only from the environment, secrets and defaults. That makes the same class usable in both places: developers keep a local `.env`, production supplies variables, and the strict `extra` check bites only where a file is actually present. It also means a mistyped `env_file` path fails silently; the `PYDANTIC_SETTINGS_DEBUG` flag logs which dotenv files were found and which were skipped. ## What to take into an interview - the error comes from **one source's reading strategy** combined with **one default**; - `extra="forbid"` is a deliberate safety net for typos, so narrow the input rather than switch the net off; - the documented version 1 compatibility setting is `extra="ignore"`.

  • Why is dotenv_filtering="match_prefix" usually better than extra="ignore" for a shared .env file?
    `extra="ignore"` drops every undeclared key, so a typo like `APP_DEBGU=true` vanishes silently. `match_prefix` passes only entries that start with the class's `env_prefix`, so other tools' entries are excluded while a misspelled entry inside your own prefix still reaches the model and fails with `extra_forbidden`.
  • With env_prefix="APP_", a developer writes debug=true in .env; what happens?
    Nothing visible. The documentation calls out this asymmetry: an unprefixed entry whose name matches a field is silently skipped. It does not set `debug`, because only `APP_DEBUG` does, and it does not raise `extra_forbidden`, whereas an unprefixed entry matching no field would raise.

  • BaseSettings ignores unknown keys by default, just like BaseModel.
  • Unknown environment variables also trigger extra_forbidden.
  • The env_prefix filters .env entries out of the box, so other tools' entries are harmless.
  • Switching to extra='ignore' has no downside for a settings class.
  • Version 1 and version 2 BaseSettings treat stray .env entries the same way.

Assumes Pydantic 2 with pydantic-settings 2.15; BaseSettings defaults to extra='forbid', and the docs name extra='ignore' as the setting for version 1 BaseSettings compatibility.