.env file loaded with python-dotenv.
Why You Need Environment Variables
Consider a naive approach:- Secrets are embedded directly in your source code.
- They will be committed to Git and potentially exposed publicly.
- Every developer working on the project has to edit the source file.
- Production, staging, and development environments all need different values.
What is a .env File?
A .env file is a plain text file that stores environment variables as KEY=VALUE pairs, one per line:
export commands in every terminal session, you write the variables once in this file.
Setting Up python-dotenv
Install the package:load_dotenv() at the very beginning of your application — before you read any environment variables:
load_dotenv() runs, every variable from .env behaves exactly like a regular OS environment variable.
Safe Variable Access
Preferos.environ.get() over os.environ[]. The get() method returns None when a variable is missing rather than raising a KeyError. You can also supply a fallback default:
Complete Example
.env
app.py
Project Structure
Sharing Projects Safely
Instead of sharing your real.env, create a template named .env.example with placeholder values:
Best Practices
Common Environment Variables
.env files are a standard practice across all major Python frameworks — FastAPI, Flask, Django, and beyond. The pattern is the same everywhere: store configuration outside your code, load it at startup, and access it via os.environ.get().