Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.3 — Configuration, Environment Variables and Secrets
Python · Example 2 of 2

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.

01

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.

02

Write require(*names) that returns a dictionary of the named environment variables, and raises a RuntimeError naming every missing one.

03

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

01

Why should configuration and secrets live outside the source code?

02

How do you read a required and an optional environment variable in Python, and what type do you get?

03

What should you do if an API key is accidentally committed to Git?

04

What is a .env file, and how do you keep it safe?

A .env file and a typed Settings object
Sign in to run this example in your browser.

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)