Python configuration management via environment variables

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Python Configuration Management cover

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

---
name: python-configuration
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.
---

# Python Configuration Management

Externalize configuration from code using environment variables and typed settings. Well-managed configuration enables the same code to run in any environment without modification.

## When to Use This Skill

- Setting up a new project's configuration system
- Migrating from hardcoded values to environment variables
- Implementing pydantic-settings for typed configuration
- Managing secrets and sensitive values
- Creating environment-specific settings (dev/staging/prod)
- Validating configuration at application startup

Overview

Externalize configuration from code using environment variables and typed settings. Well-managed configuration enables the same code to run in any environment without modification.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill python-configuration -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/python-development/skills/python-configuration
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/0d58c09c124b2cb19030/python-configuration.zip" -OutFile "$env:TEMP\python-configuration.zip"; Expand-Archive "$env:TEMP\python-configuration.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md6.1 KB
  • references/1 file · 3.9 KB
Read the files here
wshobson/4236bb92 files
SKILL.md
Show the full text212 lines

Python Configuration Management

Externalize configuration from code using environment variables and typed settings. Well-managed configuration enables the same code to run in any environment without modification.

When to Use This Skill

  • Setting up a new project's configuration system
  • Migrating from hardcoded values to environment variables
  • Implementing pydantic-settings for typed configuration
  • Managing secrets and sensitive values
  • Creating environment-specific settings (dev/staging/prod)
  • Validating configuration at application startup

Core Concepts

1. Externalized Configuration

All environment-specific values (URLs, secrets, feature flags) come from environment variables, not code.

2. Typed Settings

Parse and validate configuration into typed objects at startup, not scattered throughout code.

3. Fail Fast

Validate all required configuration at application boot. Missing config should crash immediately with a clear message.

4. Sensible Defaults

Provide reasonable defaults for local development while requiring explicit values for sensitive settings.

Quick Start

from pydantic_settings import BaseSettings
from pydantic import Field

class Settings(BaseSettings):
    database_url: str = Field(alias="DATABASE_URL")
    api_key: str = Field(alias="API_KEY")
    debug: bool = Field(default=False, alias="DEBUG")

settings = Settings()  # Loads from environment

Fundamental Patterns

Pattern 1: Typed Settings with Pydantic

Create a central settings class that loads and validates all configuration.

from pydantic_settings import BaseSettings
from pydantic import Field, PostgresDsn, ValidationError
import sys

class Settings(BaseSettings):
    """Application configuration loaded from environment variables."""

    # Database
    db_host: str = Field(alias="DB_HOST")
    db_port: int = Field(default=5432, alias="DB_PORT")
    db_name: str = Field(alias="DB_NAME")
    db_user: str = Field(alias="DB_USER")
    db_password: str = Field(alias="DB_PASSWORD")

    # Redis
    redis_url: str = Field(default="redis://localhost:6379", alias="REDIS_URL")

    # API Keys
    api_secret_key: str = Field(alias="API_SECRET_KEY")

    # Feature flags
    enable_new_feature: bool = Field(default=False, alias="ENABLE_NEW_FEATURE")

    model_config = {
        "env_file": ".env",
        "env_file_encoding": "utf-8",
    }

# Create singleton instance at module load
try:
    settings = Settings()
except ValidationError as e:
    print(f"Configuration error:\n{e}")
    sys.exit(1)

Import settings throughout your application:

from myapp.config import settings

def get_database_connection():
    return connect(
        host=settings.db_host,
        port=settings.db_port,
        database=settings.db_name,
    )
Pattern 2: Fail Fast on Missing Configuration

Required settings should crash the application immediately with a clear error.

from pydantic_settings import BaseSettings
from pydantic import Field, ValidationError
import sys

class Settings(BaseSettings):
    # Required - no default means it must be set
    api_key: str = Field(alias="API_KEY")
    database_url: str = Field(alias="DATABASE_URL")

    # Optional with defaults
    log_level: str = Field(default="INFO", alias="LOG_LEVEL")

try:
    settings = Settings()
except ValidationError as e:
    print("=" * 60)
    print("CONFIGURATION ERROR")
    print("=" * 60)
    for error in e.errors():
        field = error["loc"][0]
        print(f"  - {field}: {error['msg']}")
    print("\nPlease set the required environment variables.")
    sys.exit(1)

A clear error at startup is better than a cryptic None failure mid-request.

Pattern 3: Local Development Defaults

Provide sensible defaults for local development while requiring explicit values for secrets.

class Settings(BaseSettings):
    # Has local default, but prod will override
    db_host: str = Field(default="localhost", alias="DB_HOST")
    db_port: int = Field(default=5432, alias="DB_PORT")

    # Always required - no default for secrets
    db_password: str = Field(alias="DB_PASSWORD")
    api_secret_key: str = Field(alias="API_SECRET_KEY")

    # Development convenience
    debug: bool = Field(default=False, alias="DEBUG")

    model_config = {"env_file": ".env"}

Create a .env file for local development (never commit this):

# .env (add to .gitignore)
DB_PASSWORD=local_dev_password
API_SECRET_KEY=dev-secret-key
DEBUG=true
Pattern 4: Namespaced Environment Variables

Prefix related variables for clarity and easy debugging.

# Database configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp
DB_USER=admin
DB_PASSWORD=secret

# Redis configuration
REDIS_URL=redis://localhost:6379
REDIS_MAX_CONNECTIONS=10

# Authentication
AUTH_SECRET_KEY=your-secret-key
AUTH_TOKEN_EXPIRY_SECONDS=3600
AUTH_ALGORITHM=HS256

# Feature flags
FEATURE_NEW_CHECKOUT=true
FEATURE_BETA_UI=false

Makes env | grep DB_ useful for debugging.

Detailed worked examples and patterns

Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.

Best Practices Summary

  1. Never hardcode config - All environment-specific values from env vars
  2. Use typed settings - Pydantic-settings with validation
  3. Fail fast - Crash on missing required config at startup
  4. Provide dev defaults - Make local development easy
  5. Never commit secrets - Use .env files (gitignored) or secret managers
  6. Namespace variables - DB_HOST, REDIS_URL for clarity
  7. Import settings singleton - Don't call os.getenv() throughout code
  8. Document all variables - README should list required env vars
  9. Validate early - Check config correctness at boot time
  10. Use secrets_dir - Support mounted secrets in containers
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---
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 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillExtract text, tables, metadataXberg Document Extractionxberg-io/xberg · by xberg-ioExtract text, tables, metadata, and images from 107 document formats (PDF, Office, images, HTML, email, archives, academic) using Xberg. Use when writing code that calls Xberg APIs in Python, Node.js/TypeScript, Rust, or CLI. Covers installation, extraction (sync/async), configuration (OCR, chunking, output format), batch processing, error handling, and plugins.★ 9.4k GitHub starsSkillMove code from one implementation to another functionCode migrationkucherenko/jscpd · by kucherenkoMove code from one implementation to another function by function, tests first and code second, and check two implementations of one app for parity, with jscpd --compare as the progress measure and a coverage map binding each function to its tests. Use when porting a library or app to another language or framework (Java to Kotlin, JavaScript to Rust, a Python library to TypeScript, an iOS app to Android), when asked what is left to port, or when comparing the Android and iOS versions of an app.★ 6.3k GitHub starsSkillManages Ahrefs API usage in Python using ahrefs-pythonOpenClaudia/openclaudia-skills · by OpenClaudiaManages Ahrefs API usage in Python using `ahrefs-python` library. Use when working with SEO / marketing related tasks or with data including backlinks, keywords, domain ratings, organic traffic, site audits, rank tracking, and brand monitoring. Covers `ahrefs-python` usage including AhrefsClient / AsyncAhrefsClient, typed request/response models, error handling, and all API sections.★ 705 GitHub starsMCPDocx LLM translatoradeudealfluence/adeu · by dealfluenceDocx ↔ LLM translator. Projects .docx office files to Markdown for editing. Projects edits back to OOXML as tracked changes (redlines). Python and Node.js implementations.★ 165 GitHub starsSkillCreate an Amazon-compliant white-background main imageAmazon White-Background Main Image · 亚马逊白底主图xianyu110/ecommerce-image-skills · by xianyu110Create an Amazon-compliant white-background main image (pure #FFFFFF background, product fills ≥85% of the frame, no text, props or watermark) from a product photo with GPT Image 2.5, then verify it with a Python check script. Use for Amazon/Walmart/eBay main images, 白底图, 白底主图, hero image, listing main photo.★ 92 GitHub starsMCPOfficial monorepo of SDKs, CLISendmux sdkSendmux/sendmux-sdk · by SendmuxOfficial monorepo of SDKs, CLI, and MCP servers for Sendmux email APIs across TypeScript, Python, Go, PHP, Rust, and Ruby.★ 65 GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars