Config & Environment
Production CLIs layer configuration: defaults, config file, environment variables, and CLI flags (highest precedence). Pydantic Settings automates this pattern.
Search across all documentation pages
Production CLIs layer configuration: defaults, config file, environment variables, and CLI flags (highest precedence). Pydantic Settings automates this pattern.
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
api_url: str = "http://localhost:8000"
api_key: str = ""
debug: bool = False
model_config = {"env_prefix": "MYAPP_"}When to reach for this:
from pathlib import Path
from typing import Optional
import typer
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="INVOICE_",
env_file=".env",
env_file_encoding="utf-8",
)
api_url: str = "https://api.example.com"
api_key: str = ""
timeout: float = 30.0
output_dir: Path = Path("./output")
app = typer.Typer()
@app.command()
def sync(
api_url: Optional[str] = typer.Option(None, help="Override API URL"),
debug: bool = typer.Option(False, "--debug"),
):
settings = Settings()
if api_url:
settings = settings.model_copy(update={"api_url": api_url})
if debug:
typer.echo(f"Config: {settings.model_dump()}", err=True)
# use settings.api_url, settings.api_key, etc.
if __name__ == "__main__":
app()What this demonstrates:
.env fileenv_prefix namespaces variables (INVOICE_API_KEY)Path type for directory configuration.env file.env in .gitignore; secrets only in env vars.--help.model_dump(exclude={"api_key"}) for debug output.| Alternative | Use When | Don't Use When |
|---|---|---|
| os.environ only | Single env var | Multiple config sources |
| configparser | INI files, no deps | Validation needed |
| dynaconf | Multi-environment | Pydantic ecosystem preferred |
Pydantic Settings for typed, validated, multi-source config.
Environment variables or secret manager. Never in config files in git.
Load TOML/YAML in a callback; merge with Settings before command runs.
Optional convenience. Prefer real env vars set by orchestrator.
Generate from Settings fields; include in README and --help.
TOML preferred in Python ecosystem. YAML for complex nested config.
monkeypatch.setenv or pass overrides to Settings(_env_file=None).
env_file=".env.staging" or separate config files per env.
Pydantic parses "true", "1", "yes" as True.
Field(validation_alias=...) or @field_validator on Path fields.
Stack versions: This page was written for Python 3.14.0, FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026