1
---
2
name: python-configuration
3
description: 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
---
5
6
# Python Configuration Management
7
8
Externalize 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
23
All environment-specific values (URLs, secrets, feature flags) come from environment variables, not code.
24
25
### 2. Typed Settings
26
27
Parse and validate configuration into typed objects at startup, not scattered throughout code.
28
29
### 3. Fail Fast
30
31
Validate all required configuration at application boot. Missing config should crash immediately with a clear message.
32
33
### 4. Sensible Defaults
34
35
Provide reasonable defaults for local development while requiring explicit values for sensitive settings.
36
37
## Quick Start
38
39
```python
40
from pydantic_settings import BaseSettings
41
from pydantic import Field
42
43
class 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
48
settings = Settings() # Loads from environment
49
```
50
51
## Fundamental Patterns
52
53
### Pattern 1: Typed Settings with Pydantic
54
55
Create a central settings class that loads and validates all configuration.
56
57
```python
58
from pydantic_settings import BaseSettings
59
from pydantic import Field, PostgresDsn, ValidationError
60
import sys
61
62
class 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
87
try:
88
settings = Settings()
89
except ValidationError as e:
90
print(f"Configuration error:\n{e}")
91
sys.exit(1)
92
```
93
94
Import `settings` throughout your application:
95
96
```python
97
from myapp.config import settings
98
99
def 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
109
Required settings should crash the application immediately with a clear error.
110
111
```python
112
from pydantic_settings import BaseSettings
113
from pydantic import Field, ValidationError
114
import sys
115
116
class 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
124
try:
125
settings = Settings()
126
except 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
137
A clear error at startup is better than a cryptic `None` failure mid-request.
138
139
### Pattern 3: Local Development Defaults
140
141
Provide sensible defaults for local development while requiring explicit values for secrets.
142
143
```python
144
class 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
159
Create a `.env` file for local development (never commit this):
160
161
```bash
162
# .env (add to .gitignore)
163
DB_PASSWORD=local_dev_password
164
API_SECRET_KEY=dev-secret-key
165
DEBUG=true
166
```
167
168
### Pattern 4: Namespaced Environment Variables
169
170
Prefix related variables for clarity and easy debugging.
171
172
```bash
173
# Database configuration
174
DB_HOST=localhost
175
DB_PORT=5432
176
DB_NAME=myapp
177
DB_USER=admin
178
DB_PASSWORD=secret
179
180
# Redis configuration
181
REDIS_URL=redis://localhost:6379
182
REDIS_MAX_CONNECTIONS=10
183
184
# Authentication
185
AUTH_SECRET_KEY=your-secret-key
186
AUTH_TOKEN_EXPIRY_SECONDS=3600
187
AUTH_ALGORITHM=HS256
188
189
# Feature flags
190
FEATURE_NEW_CHECKOUT=true
191
FEATURE_BETA_UI=false
192
```
193
194
Makes the database settings easy to list for debugging. Print only the names, so no value (such as a password inside a connection URL) reaches your terminal or logs:
195
196
```bash
197
env | grep -o '^DB_[A-Za-z0-9_]*'
198
```
199
200
## Detailed worked examples and patterns
201
202
Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient.
203
204
## Best Practices Summary
205
206
1. **Never hardcode config** - All environment-specific values from env vars
207
2. **Use typed settings** - Pydantic-settings with validation
208
3. **Fail fast** - Crash on missing required config at startup
209
4. **Provide dev defaults** - Make local development easy
210
5. **Never commit secrets** - Use `.env` files (gitignored) or secret managers
211
6. **Namespace variables** - `DB_HOST`, `REDIS_URL` for clarity
212
7. **Import settings singleton** - Don't call `os.getenv()` throughout code
213
8. **Document all variables** - README should list required env vars
214
9. **Validate early** - Check config correctness at boot time
215
10. **Use secrets_dir** - Support mounted secrets in containers
216