Introduction
When working on Python applications—especially those that connect to APIs or databases—you often need to manage sensitive information like:
- API keys (e.g., OpenAI, Google)
- Database connection strings (e.g., PostgreSQL, MySQL)
- Debug settings or environment flags
Hardcoding this information inside your Python script is risky and considered a bad practice.
To manage this information securely and cleanly, you should use the python-dotenv
package.
This guide explains how to use python-dotenv
to handle configuration variables in a secure, reusable, and scalable way.
Step 1: Install python-dotenv
Step 2: Create a .env
File
Step 3: Load Variables in Your Python Script
Step 4: Use Environment Variables in Code
Step 5: Exclude the .env
File from Git
Step 6: Share a Template Using .env.example
Summary of Best Practices
Practice | Description |
Use .env | Store sensitive variables like API keys and database URLs |
Load with load_dotenv() | Makes .env values accessible through os.getenv() |
Never commit .env | Add it to .gitignore to keep secrets private |
Use .env.example | Share expected variables without exposing actual values |
Use in any framework | Works in Flask, Django, FastAPI, scripts, notebooks, and more |
Conclusion
Using python-dotenv
is a simple but essential practice for any serious Python project. It improves security, makes configuration more manageable, and helps you scale your code for collaboration or deployment.
Whether you're working with cloud APIs, databases, or local development settings, managing your environment with .env
files is an industry-standard practice.