Python Pydantic Settings Config Prompt
Replace ad-hoc os.environ access and scattered config parsing with a typed pydantic-settings model — validated env vars, .env loading, nested settings, secrets, and clear startup errors instead of runtime KeyErrors.
- Target user
- Python engineers wiring configuration into CLIs, workers, and services
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Python engineer who has eliminated entire classes of "works on my machine" bugs by making configuration typed, validated, and fail-fast at startup with pydantic-settings (v2). I will provide: - How config is read today (raw `os.environ[...]`, argparse defaults, a config.py module, a YAML/TOML file) - The settings I need (DB URL, timeouts, feature flags, API keys, log level, environment name) - My deployment surfaces (local .env, Docker env, systemd unit, CI) Your job: 1. **Model the settings** — build a `Settings(BaseSettings)` class with typed fields, sensible defaults, and `Field(...)` for required values. Use proper types: `int`/`float` for numbers, `bool` (with pydantic's truthy parsing), `HttpUrl`/`PostgresDsn`, `Literal[...]` for enums like environment, `SecretStr` for secrets so they don't leak in repr/logs. 2. **Sources & precedence** — configure `model_config = SettingsConfigDict(env_file=".env", env_prefix="APP_", env_nested_delimiter="__")`. Document precedence: explicit args > env vars > .env file > defaults. Show nested settings (e.g. `DatabaseSettings`) and how `APP_DATABASE__URL` maps to them. 3. **Validation** — add field/model validators for cross-field rules (e.g. "if TLS enabled, cert path required"), range checks on timeouts, and normalization (strip/trim, lowercase env name). Make invalid config fail loudly at construction. 4. **Fail-fast wiring** — instantiate Settings once at startup (a cached `get_settings()` with `@lru_cache`), so a missing/invalid var crashes immediately with pydantic's clear error listing every problem — not a `KeyError` deep in a request. 5. **Secrets** — show `SecretStr` usage, reading from files (`_FILE` convention / Docker secrets), and how to keep secrets out of logs and tracebacks. 6. **Migration** — map each of my current `os.environ` reads to a field and flag any that were silently optional or had string-vs-int bugs. 7. **Tests** — pytest using `monkeypatch.setenv` and overriding settings; verify defaults, required-field errors, and a nested override. Output: (a) the typed Settings model(s), (b) `get_settings()` accessor, (c) a sample `.env`, (d) my call sites migrated, (e) the pytest suite. Bias toward: fail-fast at startup, SecretStr for anything sensitive, and one source of truth for config.
Run this prompt with AI
Test it, get an AI-improved version, or compare models — live in the Prompt Workspace. No copy-paste.
Related prompts
-
Bash .env File Loader and Validator Prompt
Write a safe Bash loader that parses a .env file, validates required and typed variables, and exports them — without the security and quoting footguns of blindly sourcing untrusted env files.
-
Bash Heredoc and envsubst Config Templating Prompt
Generate config files, manifests, and scripts from templates in Bash using heredocs and envsubst — with controlled variable expansion, quoting safety, and no accidental shell interpretation of the payload.
-
Python Regex Extraction and Validation Toolkit Prompt
Build correct, readable, and well-tested regular expressions in Python for parsing logs, validating input, and extracting structured fields — with named groups, verbose mode, and catastrophic-backtracking checks.
-
Bash Dependency Preflight Check Prompt
Generate a reusable preflight block that verifies required commands, versions, env vars, and permissions before a Bash script does any real work — failing fast with actionable messages instead of cryptic mid-run errors.
More Bash & Python Automation prompts & error guides
Browse every Bash & Python Automation prompt and troubleshooting guide in one place.
Reading prompts? Get all 500 in one free PDF
500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.
- 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
- Instant PDF download — yours free, forever
- Plus one practical AI-workflow email a week (no spam)
Single opt-in · unsubscribe anytime · no spam.