Skip to content
GreenSnippets

Read typed settings from environment variables

Load configuration from the environment with defaults, type conversion and clear errors for missing values.

Python
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 exc

Example / expected output

Output
PORT = env("PORT", 8000, int)
DEBUG = env("DEBUG", False, bool)
DATABASE_URL = env("DATABASE_URL")  # required

How 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.