Load Environment Configuration With Defaults
Read required and optional settings from the environment with typed defaults, raising a clear error when a required value is missing.
Code
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
database_url: str
port: int
debug: bool
log_level: str
def load_config(environ: dict = None) -> Config:
env = environ if environ is not None else os.environ
database_url = env.get("DATABASE_URL")
if not database_url:
raise RuntimeError("DATABASE_URL is required but not set")
return Config(
database_url=database_url,
port=int(env.get("PORT", "8000")),
debug=env.get("DEBUG", "false").lower() == "true",
log_level=env.get("LOG_LEVEL", "info"),
)How it works
Load Environment Configuration With Defaults comes down to the class Config and the function load_config.
Invalid states are rejected up front: it throws RuntimeError instead of continuing with bad data.
What to watch for
- The guard
not database_urlshort-circuits the flow with an earlyraisewhen its condition holds.
Using it
The entry-point signature is def load_config(environ: dict = None) -> Config
load_config is the public entry point; everything else in the file exists to support it.
Key statements
return Config(
database_url=database_url,
port=int(env.get("PORT", "8000")),
debug=env.get("DEBUG", "false").lower() == "true",
log_level=env.get("LOG_LEVEL", "info"),
)
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Gitignore Template BuilderCompose clean .gitignore files by combining Node, Python, Go, Rust, Java, OS, IDE, and Docker presets with deduplication and custom rules.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What happens on invalid input?
- Validation comes first — `RuntimeError` marks the failure at `not database_url`, before any partial work happens.
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `os`, `dataclasses`. The file defines `load_config` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.