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.

PythonConfig Management

Code

pythonsnippet
23 lines
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_url short-circuits the flow with an early raise when 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

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.