Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.8 — Laying Out a Real Project
Python · Example 2 of 2

Settings from the environment, secrets kept quiet

A tiny .env reader. setdefault means a variable that is already set wins over the file, which is the rule on real servers. The class never prints the key itself, only whether it is set. The key shown in the file is a fake placeholder. class Settings: (Phase 8 teaches classes) is read here as "one labelled bundle of settings", and __repr__ is the method that decides what print(Settings()) shows. key, _, value = line.partition("=") splits a line at the first = (Topic 3.2).

A real project has a predictable shape: code in src/<package>/, tests in tests/, a pyproject.toml, a README, a .gitignore, and settings and secrets kept out of the code. It runs with python -m package or an installed command.

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 5 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 the lines of a .gitignore file that keep these out of git: the .venv folder, the __pycache__ folders with the .pyc files inside, and the .env file.

02

Write code that reads the environment variable PORT, turns it into an integer, and uses 8000 when PORT is not set. Print the number.

03

Write the full content of a __main__.py file, in the package stockbox, that imports main from the module cli of the same package (use an absolute import) and calls it.

Explain it without notes

01

Describe the src/ layout and why it is preferred.

02

What is the difference between python script.py and python -m package, and what is __main__.py?

03

How should configuration and secrets be handled in a Python project?

04

What should be in .gitignore for a Python project, and why?

Settings from the environment, secrets kept quiet
Sign in to run this example in your browser.

Expected output

Settings(app_name='stockbox', low_limit=2, api_key=set)
secret never printed: True