PythiloLesson 11 of 15 · progress kept in this browser

Settings from the environment

Passwords, API keys and server addresses do not belong in code. Programs read them from environment variables, which a shell, a container or a hosting service sets. During development a .env file holds the same names, and it is kept out of version control.

import os

os.environ["APP_PORT"] = "8080"
port = int(os.environ.get(
    "APP_PORT", "8000"))
debug = os.environ.get("APP_DEBUG") == "1"
print(port, debug)
  • os.environ behaves like a dict of strings. Convert numbers and flags yourself.
  • .get(name, default) suits optional settings. For a required one, index with [name], so a missing value fails at startup.
  • A real variable overrides the .env file, so a server can change one value without anyone editing files.
Your task

Write load_settings(text, environ) that parses .env text into a dict: skip blank lines and # comments, drop an export prefix, split at the first =, strip spaces, and remove one pair of matching quotes around the value. A key that also appears in environ (a mapping such as os.environ) takes the value from there.