Typed Config from Environment Variables

medium
Unit 20 · Timing0/3 to milestone

Twelve-factor apps read configuration from environment variables, which are all strings. Build a typed loader that reports every problem at once instead of failing on the first.

spec maps field names to (type, default), where the default is REQUIRED if there isn't one. Types are int, float, bool, str and list (comma-separated, items stripped, empty items dropped). Implement load_config(spec, env, prefix="APP_"):

  • The variable for field port is APP_PORT (prefix plus the upper-cased name).
  • Missing variables use the default (which is not converted). A missing required field is an error.
  • Booleans accept true/false/1/0/yes/no/on/off in any case.
  • Collect all errors as "APP_PORT: expected int" or "APP_SECRET: required", and raise a ValueError whose message joins them with "; " in spec order. Otherwise return the dict of values.
#configuration#parsing#validation2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Typed Config from Environment Variables · TechGradify