The problem they solve
- Secrets are visible in your code and Git history
- You can’t safely share your code with others
- Different machines need different settings but require code changes
How environment variables work
Environment variables live in your operating system, not in your code:Setting them in the terminal
You can set environment variables temporarily from the terminal:.env files (covered on the next page) are a better approach for persistent configuration.
Reading environment variables in Python
Common uses
- API keys —
OPENAI_API_KEY,GITHUB_TOKEN,STRIPE_SECRET_KEY - Database URLs —
DATABASE_URL,REDIS_URL - App settings —
DEBUG=True,PORT=8000,LOG_LEVEL=INFO - File paths —
LOG_DIR,UPLOAD_FOLDER
Important rules
- Environment variables are always strings — if you need a number or boolean, convert them explicitly (
int(os.environ.get("PORT", "8000"))) - Names are UPPERCASE by convention
- Values are machine-specific — your
DATABASE_URLwill be different from a teammate’s - They don’t persist between terminal sessions unless you set them in a shell profile or use a
.envfile
What’s next?
Setting variables by hand every session is tedious..env files give you a much cleaner workflow.
Using .env files
The easier way to manage environment variables