Using .env files
The easy way to manage secrets
When you write Python code, you often need to store secret keys or configuration values. Let's learn an easy and safe way to handle them.
What is a .env file?
A .env file is a plain text file. It holds environment variables. Think of it as a small file that tells your program important setup details.
It keeps sensitive information, like API keys or database passwords, separate from your main code. This is super important for security and flexibility.
.env means it's often hidden by default on many operating systems. Don't worry, your Python code can still find it!Basic setup
Let's get your project ready to use .env files.
1. Install python-dotenv
First, you need a small library called python-dotenv. It helps your Python code read these special files.
pip install python-dotenv2. Create .env file
In the root (top-level) directory of your Python project, create a new file named .env. Make sure it's exactly .env, with the dot!
Inside this .env file, add your variables. Each line is a KEY=VALUE pair. No spaces around the equals sign, usually.
API_KEY=your_super_secret_api_key_123
DATABASE_URL=postgres://user:pass@host:port/dbname
DEBUG_MODE=True3. Load in Python
Now, in your Python script, you need to tell python-dotenv to load the variables from your .env file.
from dotenv import load_dotenv
import os
load_dotenv() # take environment variables from .env.
api_key = os.getenv("API_KEY")
debug_mode = os.getenv("DEBUG_MODE")
print(f"API Key: {api_key}")
print(f"Debug Mode: {debug_mode}")The load_dotenv() function looks for the .env file. Then, os.getenv() fetches the values for you. It's that simple!
Critical: Add to .gitignore
To prevent accidentally sharing your secrets, add .env to your project's .gitignore file. This tells Git to ignore it.
# Ignore environment files
.env
*.envComplete example
Here's how a small project might look with a .env file and a Python script using it.
# .env file
SECRET_KEY=my_super_secret_key
DATABASE_USER=admin# main.py
from dotenv import load_dotenv
import os
load_dotenv()
secret = os.getenv("SECRET_KEY")
db_user = os.getenv("DATABASE_USER")
print(f"Using secret: {secret}")
print(f"Database user: {db_user}")Show others what they need
When you share your project, others need to know which environment variables to set. You can provide an example file.
Create a file called .env.example (or .env.sample). This file has the same keys as your .env but with empty or placeholder values.
# .env.example
API_KEY=
DATABASE_URL=
DEBUG_MODE=False # Example defaultThis file *can* be committed to Git. It helps other developers understand what variables they need to create in their *own* .env file.
Rules for .env files
- One
KEY=VALUEpair per line. - No spaces around
=might be slightly safer, thoughpython-dotenvoften handles them. - String values usually don't need quotes, but if they contain spaces or special characters, you can use single or double quotes.
- Lines starting with
#are comments and are ignored.
# This is a comment
MY_VARIABLE=hello world # This comment here might be ignored by some tools
ANOTHER_VAR="value with spaces"
HTTP_PORT=8080Common patterns
It's common to have different .env files for different environments (e.g., development, testing, production). However, for beginners, one .env for local development is usually enough.
You often retrieve values at the start of your main script or an app.py file.
Quick tips
- Always use
os.getenv()to fetch variables, notos.environdirectly, asgetenvreturnsNoneif the variable isn't set, which is safer. - Convert string values to the correct type (e.g.,
'True'toTrue,'123'to123) in your Python code.
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv("API_KEY")
DEBUG = os.getenv("DEBUG_MODE", "False").lower() == "true" # Provide a default
PORT = int(os.getenv("PORT", 8000)) # Convert to integer
print(f"Debug is {DEBUG}, Port is {PORT}")What's next?
Now you know how to keep your secrets safe and your configurations flexible using .env files. This is a crucial skill for any developer!
Practice adding a .env file to your next project. Try storing different types of data and retrieving them.