Read typed settings from environment variables
Load configuration from the environment with defaults, type conversion and clear errors for missing values.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
import os
def env(name, default=None, cast=str):
raw = os.environ.get(name)
if raw is None or raw == "":
if default is None:
raise RuntimeError(f"Missing required environment variable {name}")
return default
if cast is bool:
return raw.strip().lower() in {"1", "true", "yes", "on"}
try:
return cast(raw)
except ValueError as exc:
raise RuntimeError(f"Environment variable {name} must be {cast.__name__}") from excExample / expected output
PORT = env("PORT", 8000, int)
DEBUG = env("DEBUG", False, bool)
DATABASE_URL = env("DATABASE_URL") # requiredHow it works
Configuration that varies between deployments belongs in environment variables. Converting and validating at startup fails fast with a readable message instead of crashing later. Never log secret values.
Related snippets
- TypeScript Tested
Check an object against a type with satisfies
Validate a config object against an interface while keeping its precise literal types.
- Python Tested
Token bucket rate limiter
Allow bursts but cap the sustained request rate with a small thread-safe token bucket.
- Python Tested
Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.
- Python Tested
Slugify a string
Turn text into a lowercase, hyphenated, ASCII-only slug using only the standard library.

