Skills · Coding

Python Configuration Management

Unverified30/40

Python configuration management via environment variables and typed settings. Use when externalizing config, setting up pydantic-settings, managing secrets, or implementing environment-specific behavior.

Originally by wshobson · MIT

Claude CodePartialHas SKILL.md but declares no allowed-tools — Claude Code will ask for permission each time
Cursor·UnknownWe have not crawled the repo tree, so we will not guess
Codex·UnknownWe have not crawled the repo tree, so we will not guess
Gemini CLI·UnknownThe spec defines no detection rule for Gemini
Copilot·UnknownWe have not crawled the repo tree, so we will not guess
npx agentalley add python-configuration

This command does not work yet — the CLI is still being built. Until then, use Raw in the reader below to take the file.

Who is stuck, and on what

Python configuration management via environment variables and typed settings. Use when externalizing config, setting up pydantic-settings, managing secrets, or implementing environment-specific behavior.

The whole source

No sign-in, no blur, nothing truncated
python-configuration/SKILL.md212 lines6.1 KBRawView on GitHub
Frontmatter — 2 properties
namepython-configuration
descriptionPython configuration management via environment variables and typed settings. Use when externalizing config, setting up pydantic-settings, managing secrets, or implementing environment-specific behavior.
1---
2name: python-configuration
3description: Python configuration management via environment variables and typed settings. Use when externalizing config, setting up pydantic-settings, managing secrets, or implementing environment-specific behavior.
4---A5No allowed-tools declared — no way to tell what this skill may touch
5 
6# Python Configuration Management
7 
8Externalize configuration from code using environment variables and typed settings. Well-managed configuration enables the same code to run in any environment without modification.
9 
10## When to Use This Skill
11 
12- Setting up a new project's configuration system
13- Migrating from hardcoded values to environment variables
14- Implementing pydantic-settings for typed configuration
15- Managing secrets and sensitive values
16- Creating environment-specific settings (dev/staging/prod)
17- Validating configuration at application startup
18 
19## Core Concepts
20 
21### 1. Externalized Configuration
22 
23All environment-specific values (URLs, secrets, feature flags) come from environment variables, not code.
24 
25### 2. Typed Settings
26 
27Parse and validate configuration into typed objects at startup, not scattered throughout code.
28 
29### 3. Fail Fast
30 
31Validate all required configuration at application boot. Missing config should crash immediately with a clear message.
32 
33### 4. Sensible Defaults
34 
35Provide reasonable defaults for local development while requiring explicit values for sensitive settings.
36 
37## Quick Start
38 
39```python
40from pydantic_settings import BaseSettings
41from pydantic import Field
42 
43class Settings(BaseSettings):
44 database_url: str = Field(alias="DATABASE_URL")
45 api_key: str = Field(alias="API_KEY")
46 debug: bool = Field(default=False, alias="DEBUG")
47 
48settings = Settings() # Loads from environment
49```
50 
51## Fundamental Patterns
52 
53### Pattern 1: Typed Settings with Pydantic
54 
55Create a central settings class that loads and validates all configuration.
56 
57```python
58from pydantic_settings import BaseSettings
59from pydantic import Field, PostgresDsn, ValidationError
60import sys
61 
62class Settings(BaseSettings):
63 """Application configuration loaded from environment variables."""
64 
65 # Database
66 db_host: str = Field(alias="DB_HOST")
67 db_port: int = Field(default=5432, alias="DB_PORT")
68 db_name: str = Field(alias="DB_NAME")
69 db_user: str = Field(alias="DB_USER")
70 db_password: str = Field(alias="DB_PASSWORD")
71 
72 # Redis
73 redis_url: str = Field(default="redis://localhost:6379", alias="REDIS_URL")
74 
75 # API Keys
76 api_secret_key: str = Field(alias="API_SECRET_KEY")
77 
78 # Feature flags
79 enable_new_feature: bool = Field(default=False, alias="ENABLE_NEW_FEATURE")
80 
81 model_config = {
82 "env_file": ".env",
83 "env_file_encoding": "utf-8",
84 }
85 
86# Create singleton instance at module load
87try:
88 settings = Settings()
89except ValidationError as e:
90 print(f"Configuration error:\n{e}")
91 sys.exit(1)
92```
93 
94Import `settings` throughout your application:
95 
96```python
97from myapp.config import settings
98 
99def get_database_connection():
100 return connect(
101 host=settings.db_host,
102 port=settings.db_port,
103 database=settings.db_name,
104 )
105```
106 
107### Pattern 2: Fail Fast on Missing Configuration
108 
109Required settings should crash the application immediately with a clear error.
110 
111```python
112from pydantic_settings import BaseSettings
113from pydantic import Field, ValidationError
114import sys
115 
116class Settings(BaseSettings):
117 # Required - no default means it must be set
118 api_key: str = Field(alias="API_KEY")
119 database_url: str = Field(alias="DATABASE_URL")
120 
121 # Optional with defaults
122 log_level: str = Field(default="INFO", alias="LOG_LEVEL")
123 
124try:
125 settings = Settings()
126except ValidationError as e:
127 print("=" * 60)
128 print("CONFIGURATION ERROR")
129 print("=" * 60)
130 for error in e.errors():
131 field = error["loc"][0]
132 print(f" - {field}: {error['msg']}")
133 print("\nPlease set the required environment variables.")
134 sys.exit(1)
135```
136 
137A clear error at startup is better than a cryptic `None` failure mid-request.
138 
139### Pattern 3: Local Development Defaults
140 
141Provide sensible defaults for local development while requiring explicit values for secrets.
142 
143```python
144class Settings(BaseSettings):
145 # Has local default, but prod will override
146 db_host: str = Field(default="localhost", alias="DB_HOST")
147 db_port: int = Field(default=5432, alias="DB_PORT")
148 
149 # Always required - no default for secrets
150 db_password: str = Field(alias="DB_PASSWORD")
151 api_secret_key: str = Field(alias="API_SECRET_KEY")
152 
153 # Development convenience
154 debug: bool = Field(default=False, alias="DEBUG")
155 
156 model_config = {"env_file": ".env"}
157```
158 
159Create a `.env` file for local development (never commit this):
160 
161```bash
162# .env (add to .gitignore)
163DB_PASSWORD=local_dev_password
164API_SECRET_KEY=dev-secret-key
165DEBUG=true
166```
167 
168### Pattern 4: Namespaced Environment Variables
169 
170Prefix related variables for clarity and easy debugging.
171 
172```bash
173# Database configuration
174DB_HOST=localhost
175DB_PORT=5432
176DB_NAME=myapp
177DB_USER=admin
178DB_PASSWORD=secret
179 
180# Redis configuration
181REDIS_URL=redis://localhost:6379
182REDIS_MAX_CONNECTIONS=10
183 
184# Authentication
185AUTH_SECRET_KEY=your-secret-key
186AUTH_TOKEN_EXPIRY_SECONDS=3600
187AUTH_ALGORITHM=HS256
188 
189# Feature flags
190FEATURE_NEW_CHECKOUT=true
191FEATURE_BETA_UI=false
192```
193 
194Makes `env | grep DB_` useful for debugging.
195 
196## Detailed worked examples and patterns
197 
198Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient.
199 
200## Best Practices Summary
201 
2021. **Never hardcode config** - All environment-specific values from env vars
2032. **Use typed settings** - Pydantic-settings with validation
2043. **Fail fast** - Crash on missing required config at startup
2054. **Provide dev defaults** - Make local development easy
2065. **Never commit secrets** - Use `.env` files (gitignored) or secret managers
2076. **Namespace variables** - `DB_HOST`, `REDIS_URL` for clarity
2087. **Import settings singleton** - Don't call `os.getenv()` throughout code
2098. **Document all variables** - README should list required env vars
2109. **Validate early** - Check config correctness at boot time
21110. **Use secrets_dir** - Support mounted secrets in containers
212 

Reviews

Installed this one?Write the first review and take the Trailblazer badge.

Reviews only open after a real install, so this is empty — and we leave it empty rather than invent one.

Alternatives

Also in Coding