Pydantic Settings Environment Variables
Load typed configuration from environment variables with pydantic-settings, layering dotenv files and validating on import.
Code
from functools import lru_cache
from pydantic import Field, PostgresDsn, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict
class AppSettings(BaseSettings):
model_config = SettingsConfigDict(
env_file=('.env.defaults', '.env'),
env_file_encoding='utf-8',
env_prefix='APP_',
extra='ignore',
case_sensitive=False,
)
environment: str = Field(default='development', pattern='^(dev|staging|prod)$')
debug: bool = False
database_dsn: PostgresDsn
pool_size: int = Field(default=10, ge=1, le=100)
log_level: str = Field(default='info', pattern='^(debug|info|warning|error)$')
@lru_cache
def get_settings() -> AppSettings:
try:
return AppSettings()
except ValidationError as exc:
errors = '; '.join(
f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}"
for e in exc.errors()
)
raise SystemExit(f'invalid configuration -> {errors}') from exc
settings = get_settings()
print('running in', settings.environment, 'pool', settings.pool_size)How it works
Pydantic Settings Environment Variables is built around the class AppSettings and the function get_settings.
Repetition is confined to for e in exc.errors() — the rest of the file is straight-line. lru_cache, Field, PostgresDsn, ValidationError, BaseSettings are the only symbols borrowed from pydantic — the coupling is explicit and narrow. A SystemExit is raised inside an except block, so it is conditional on that failure being handled in the first place.
Caveats
- External dependency:
pydanticandpydantic_settings— install them before running the snippet.
Applying it
Signature: def get_settings() -> AppSettings
The demo output is labeled (running in), so every printed line maps back to its originating operation.
get_settings is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def get_settings() -> AppSettings:
try:
return AppSettings()
except ValidationError as exc:
errors = '; '.join(
f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}"
for e in exc.errors()
)
raise SystemExit(f'invalid configuration -> {errors}') from exc
Interactive Tools for This Topic
FAQ
- When is the exception raised?
- Inside an `except` handler — the `SystemExit` fires only while that failure type is already being handled, not on its own trigger.
- Do I need to install anything before running this?
- Yes: `pydantic` and `pydantic_settings` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.