A .env file and a typed Settings object
The program writes a fake .env file, reads it, and builds settings. The first attempt fails with a clear list of what is missing. @dataclass and @classmethod are explained in Topics 8.8 and 8.3; setdefault (Topic 4.4) sets a key only if it is not there yet.
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
before loading: missing environment variables: APP_ENV, LLM_API_KEY
app_env: dev
timeout: 15.0
Settings(app_env='dev', api_key='fake-key-abcdef123456', timeout_seconds=15.0)