Pydantic Settings source contracts
Treat settings as two ordered phases:
configured sources -> candidate field values -> Pydantic validation -> Settings
BaseSettings is an application configuration boundary, not a global service
locator. Instantiate it once near the composition root and inject the validated
result.
Workflow
- Inspect the installed
pydantic-settings and Pydantic versions separately.
Do not infer one package's API from the other.
- Define the settings ownership boundary, field types, required values,
defaults, environment prefix, case policy, nested delimiter, dotenv policy,
secrets source, CLI use, and extra-key behavior.
- List every enabled source and its required priority. Use the documented
defaults only when they match the application contract; otherwise implement
and test
settings_customise_sources explicitly.
- Use nested Pydantic models for nested configuration. Use Pydantic secret
types for sensitive values, but do not mistake redacted representation for
storage or access control.
- Keep I/O, network secret retrieval, and business logic out of validators.
Add a narrow custom source only when built-in sources cannot express the
input contract.
- Test each source alone, source collisions, malformed values, missing
required fields, unknown dotenv keys, nested overrides, secret redaction,
and isolated environment/filesystem state.
Canonical application boundary
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class DatabaseSettings(BaseModel):
host: str
port: int = 5432
password: SecretStr
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="APP_",
env_nested_delimiter="__",
env_file=".env",
extra="forbid",
)
debug: bool = False
database: DatabaseSettings
def load_settings() -> Settings:
return Settings()
Do not manually call os.getenv inside validators. Complex environment values
can use JSON decoding; nested keys override the matching top-level JSON subkey.
If a different grammar is required, make it explicit and reject ambiguity.
Source priority
Default priority can include CLI arguments when enabled, then initializer,
environment, dotenv, secrets directory, and defaults. Verify current docs and
the installed signature before relying on the exact sequence. When policy says
environment must override initializer values, return the sources in that exact
order from settings_customise_sources and test a collision.
Never commit production secrets in .env, log a settings dump, or claim that
SecretStr encrypts data. Secrets-directory file permissions, rotation, and
provider authorization remain external controls.
Completion requires isolated tests of names, conversion, nesting, precedence,
extras, missing and malformed values, and secret exposure. Read the source
model, settings recipes,
and verification matrix for nontrivial configurations.
1---2name: pydantic-settings-python3description: >-4 Use for writing, reviewing, debugging, migrating, or testing Python5 application configuration built with pydantic-settings. Trigger for6 BaseSettings, SettingsConfigDict, environment names, dotenv, secrets7 directories, nested settings, CLI sources, custom source precedence, and8 secret-safe startup configuration. Do not use for ordinary Pydantic model9 validation, direct os.environ access in a small script, or external secret10 manager administration.11argument-hint: "[settings model, sources, precedence, or configuration failure]"12metadata:13 source: https://skillmd.com/skills/schattenspiegel/pydantic-settings-python14---1516# Pydantic Settings source contracts1718Treat settings as two ordered phases:1920```text21configured sources -> candidate field values -> Pydantic validation -> Settings22```2324`BaseSettings` is an application configuration boundary, not a global service25locator. Instantiate it once near the composition root and inject the validated26result.2728## Workflow29301. Inspect the installed `pydantic-settings` and Pydantic versions separately.31 Do not infer one package's API from the other.322. Define the settings ownership boundary, field types, required values,33 defaults, environment prefix, case policy, nested delimiter, dotenv policy,34 secrets source, CLI use, and extra-key behavior.353. List every enabled source and its required priority. Use the documented36 defaults only when they match the application contract; otherwise implement37 and test `settings_customise_sources` explicitly.384. Use nested Pydantic models for nested configuration. Use Pydantic secret39 types for sensitive values, but do not mistake redacted representation for40 storage or access control.415. Keep I/O, network secret retrieval, and business logic out of validators.42 Add a narrow custom source only when built-in sources cannot express the43 input contract.446. Test each source alone, source collisions, malformed values, missing45 required fields, unknown dotenv keys, nested overrides, secret redaction,46 and isolated environment/filesystem state.4748## Canonical application boundary4950```python51from pydantic import BaseModel, SecretStr52from pydantic_settings import BaseSettings, SettingsConfigDict535455class DatabaseSettings(BaseModel):56 host: str57 port: int = 543258 password: SecretStr596061class Settings(BaseSettings):62 model_config = SettingsConfigDict(63 env_prefix="APP_",64 env_nested_delimiter="__",65 env_file=".env",66 extra="forbid",67 )6869 debug: bool = False70 database: DatabaseSettings717273def load_settings() -> Settings:74 return Settings()75```7677Do not manually call `os.getenv` inside validators. Complex environment values78can use JSON decoding; nested keys override the matching top-level JSON subkey.79If a different grammar is required, make it explicit and reject ambiguity.8081## Source priority8283Default priority can include CLI arguments when enabled, then initializer,84environment, dotenv, secrets directory, and defaults. Verify current docs and85the installed signature before relying on the exact sequence. When policy says86environment must override initializer values, return the sources in that exact87order from `settings_customise_sources` and test a collision.8889Never commit production secrets in `.env`, log a settings dump, or claim that90`SecretStr` encrypts data. Secrets-directory file permissions, rotation, and91provider authorization remain external controls.9293Completion requires isolated tests of names, conversion, nesting, precedence,94extras, missing and malformed values, and secret exposure. Read [the source95model](references/settings.md), [settings recipes](references/recipes-settings.md),96and [verification matrix](references/testing.md) for nontrivial configurations.