.env file.
Why Not Hardcode Configuration?
- Secrets are exposed to anyone who reads your code.
- Values may accidentally be committed to a public repository.
- Every developer on the team must edit source files to use different values.
- Different environments (development, testing, production) require different settings.
What Are Environment Variables?
Environment variables are key-value pairs maintained by the operating system. They are available to every program running in that environment, and your Python code simply requests them by name:Setting Variables Manually (macOS / Linux)
What Is a .env File?
A .env file is a plain text file that stores environment variables so you only have to write them once:
.env files automatically. You need the python-dotenv package.
Setting Up python-dotenv
1
Install the package
2
Create your .env file
3
Load and read the variables
load_dotenv() once at the beginning of your application, before any other code reads from the environment.Reading Variables Safely
Preferos.environ.get() over os.environ["KEY"]. The get() form returns None instead of crashing when a variable is missing. You can also supply a fallback default:
Complete Example
.env
app.py
Never Commit .env to Git
Sharing Projects Safely
Instead of sharing your real.env, create a template named .env.example with placeholder values and commit that instead:
Recommended Project Structure
Best Practices
Naming conventions
Naming conventions
- Use UPPERCASE names:
DATABASE_URL,API_KEY,SECRET_KEY - One variable per line
- No spaces around
=: writePORT=8000, notPORT = 8000 - Use
#comments to group related variables
Common variables to expect
Common variables to expect
Quick checklist
Quick checklist
- Call
load_dotenv()at the very start of your application. - Use
os.environ.get()instead of hardcoding values. - Never commit
.envto GitHub. - Share
.env.exampleinstead. - Keep all configuration outside your source files.
.env files is a standard practice in modern Python development — you’ll find it in FastAPI, Flask, Django, and virtually every other framework.