Bootstrap a Reproducible Python Workspace and Starter Service
System DesignModel answerLast updated
Describe how to take a fresh machine to a pinned, secure, fast-feedback Python workspace and prove it works by scaffolding a small tested CLI and HTTP service.
You are handed a brand-new laptop and told you will be writing Python in a live, timed session where AI coding assistants are permitted. Walk through how you would get from nothing to a dependable working setup, and explain why you chose each tool.
Cover these five areas:
- Interpreter and isolation. Install a Python version manager and create an isolated, project-specific environment pinned to an exact interpreter version.
- Secrets. Describe how API keys and other credentials are supplied to the program without ending up in version control, logs, or AI prompts.
- Rapid feedback. Set up automatic formatting, linting, testing, and live reload so that each edit gives you feedback within seconds.
- Reproducibility. Make the setup repeatable for anyone who clones the project, using a dependency lockfile and a single command entry point (Makefile or scripts).
- Validation. Scaffold a tiny service that exposes the same logic through both a command-line interface and an HTTP endpoint, with tests, to confirm the whole toolchain works end to end.
For each decision, justify it against at least one alternative and point out the typical mistakes people make.
Hints
Hint 1
Pick one tool per concern: one for the interpreter version, one for package isolation, one for locking, one for lint/format, one for tests, and one front door for running commands.
Hint 2
Treat secrets as configuration, not code: commit a template with placeholder names, ignore the real file, read values from the process environment, and fail immediately when a required one is absent.
Hint 3
Your scaffold should prove each layer: a pure function with unit tests, a CLI wrapper, an HTTP wrapper, and a check that the health endpoint never reveals the secret value.
Hint 4
Think about what breaks on a fresh clone: unpinned transitive dependencies, a missing interpreter version, Makefile tabs, shell init not reloaded, and the wrong pip being used.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Guiding principle
The goal is to go from a blank machine to a working, tested service quickly and identically every time. I follow one tool per concern, so there is never ambiguity about which command does what:
| Concern | Tool |
|---|---|
| Interpreter version | pyenv |
| Package isolation | stdlib venv |
| Dependency locking | pip-tools |
| Format and lint | ruff |
| Tests | pytest |
| Command entry point | make |
uv can replace pyenv, venv, and pip-tools in one much faster tool. I would mention it, but keep the classic path as a fallback in case the environment restricts it.
1. Interpreter and isolation
brew install pyenv openssl readline xz # macOS; on Linux install build deps first
echo 'eval "$(pyenv init -)"' >> ~/.zshrc && exec zsh
pyenv install 3.12.4
mkdir svc && cd svc
pyenv local 3.12.4 # writes .python-version (commit it)
python -m venv .venv && source .venv/bin/activate
python -m pip install -U pip pip-tools
- pyenv pins the exact patch version per project without touching the system Python, and
.python-versiondocuments the pin for everyone. venvneeds no extra install and is understood everywhere.- Always use
python -m pipso packages go into the active interpreter.
Pitfalls: forgetting to reload the shell after editing the rc file, missing compiler headers on Linux (the build fails), and installing into the system Python by accident.
2. Secrets
- Commit
.env.examplecontaining names and fake values only. - Keep the real
.envin.gitignore. - Load it with
python-dotenvin development only; real environment variables take precedence in production. - Read via
os.environand fail fast when a required key is missing, rather than failing later with an obscure error. - Never print or log values. A health endpoint may report whether a key is configured, not its content.
- For long-lived keys use the OS keychain or a secrets manager;
direnvis handy for per-directory loading. - With AI assistants, exclude
.envfrom the context they can read and never paste it into a prompt.
Pitfalls: committing .env before adding it to .gitignore (it stays in history), echoing config in debug logs, and hard-coding a "temporary" key.
3. Fast feedback loop
ruff formatandruff check --fixreplace black, isort, and flake8 in a single Rust binary that runs in milliseconds.pytest -x -qstops at the first failure with minimal output.pytest-watch(ptw) reruns tests on every save.uvicorn app:app --reloadrestarts the server on code changes.- Optionally add
pre-committo run ruff on each commit. In a timed session the save-triggered loop matters more.
4. Reproducibility
requirements.inlists direct dependencies only (fastapi, uvicorn, python-dotenv, httpx, pytest, pytest-watch, ruff).pip-compile --generate-hashescreates a fully pinnedrequirements.txtincluding transitive dependencies and hashes.pip-syncmakes the venv match the lockfile exactly and removes strays.- A Makefile gives a single entry point:
.PHONY: setup lock fmt lint test watch run check
setup:
python -m pip install -U pip pip-tools
pip-sync requirements.txt
lock:
pip-compile --generate-hashes -o requirements.txt requirements.in
fmt:
ruff format . && ruff check --fix .
lint:
ruff check . && ruff format --check .
test:
pytest -x -q
watch:
ptw -- -x -q
run:
uvicorn app:app --reload
check: lint test
Recipe lines must start with a tab, a classic source of confusing errors. A fresh clone then needs only make setup && make check.
5. Validation scaffold
I build a small number-summary service so there is real logic to test. The core is a pure function; the CLI and HTTP layers are thin wrappers.
# app.py
from __future__ import annotations
import argparse, json, os, statistics, sys
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
load_dotenv()
def get_api_key() -> str:
key = os.environ.get("API_KEY")
if not key:
raise RuntimeError("API_KEY is not set (see .env.example)")
return key
def summarize(values: list[float]) -> dict[str, float]:
if not values:
raise ValueError("values must be non-empty")
return {"count": len(values), "mean": statistics.fmean(values),
"median": statistics.median(values),
"min": min(values), "max": max(values)}
class SummaryRequest(BaseModel):
values: list[float]
app = FastAPI()
@app.get("/health")
def health():
return {"ok": True, "api_key_configured": bool(os.environ.get("API_KEY"))}
@app.post("/summary")
def summary(req: SummaryRequest):
try:
return summarize(req.values)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
def main(argv=None) -> int:
p = argparse.ArgumentParser()
p.add_argument("values", nargs="+", type=float)
print(json.dumps(summarize(p.parse_args(argv).values)))
return 0
if __name__ == "__main__":
sys.exit(main())
Tests should cover: a normal summary, the empty-input error (ValueError and HTTP 422), the CLI output via capsys, the missing-key failure via monkeypatch.delenv, and that /health never contains the secret value.
Smoke test:
make lock setup check
python app.py 1 2 3
make run && curl -s localhost:8000/health
Trade-offs and common mistakes
- uv vs pyenv + pip-tools: uv is faster and unifies tooling, but pyenv + pip-tools is more widely known and safe if uv is unavailable.
- Hash-pinned lockfiles add safety but make ad-hoc installs slightly more tedious.
- Over-tooling: in a short session, skip heavy extras (Docker, CI) unless asked; a working loop beats an elaborate one.
- Do the setup before the session, then verify it once from a clean clone so you know it truly reproduces.
- Do not let AI-generated code or config bypass your checks; run
make checkafter every significant change.