os.environ: required, optional and masked
The key is fake. The mask function is what you would use before putting a key into a log line.
Settings that change between your laptop, a test server and production (and secrets such as API keys) should live outside the code, in environment variables, and be read once into a typed settings object. A secret that is committed to Git must be treated as stolen.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write get_bool(name, default=False) that reads an environment variable and returns True for 1, true or yes in any capitals, False for anything else, and default when unset.
Write require(*names) that returns a dictionary of the named environment variables, and raises a RuntimeError naming every missing one.
Write mask(secret) that keeps the first 3 and last 2 characters of a key longer than 8 characters, and returns *** for shorter ones.
Explain it without notes
Why should configuration and secrets live outside the source code?
How do you read a required and an optional environment variable in Python, and what type do you get?
What should you do if an API key is accidentally committed to Git?
What is a .env file, and how do you keep it safe?
Expected output
APP_ENV: dev
DEBUG with default: 0
DEBUG is None? True
KeyError for missing variable: 'DATABASE_URL'
key in a log line: fake...56