.env Files and python-dotenv
Loading .env files, .gitignore rules, and dotenv best practices.
.env Files and python-dotenv is a free AI Agents lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Problem with Shell Exports
Setting environment variables with export in the shell works, but it requires re-setting them in every new terminal session. Managing many variables this way is error-prone and not shareable with teammates.
.env files solve this by storing all project variables in one file that is loaded automatically.
The .env File Format
A .env file contains KEY=VALUE pairs, one per line. Lines starting with # are comments. Values can optionally be quoted. This simple format is understood by dozens of tools and frameworks.
# .env file (NEVER commit this file to git)
# Required API keys
OPENAI_API_KEY=sk-proj-your-real-key-here
SEARCH_API_KEY=tvly-your-tavily-key-here
# Optional settings with defaults
AGENT_MODEL=gpt-4o-mini
AGENT_MAX_STEPS=20
LOG_LEVEL=DEBUG
# Database (optional — disables memory storage if not set)
# DATABASE_URL=postgresql://user:pass@localhost/agentdb
# Environment identifier
ENV=developmentLoading .env with python-dotenv
Install python-dotenv with pip install python-dotenv. Call load_dotenv() at the very top of your entry point before any os.environ reads. It loads the .env file and populates the environment.
# pip install python-dotenv
from dotenv import load_dotenv
import os
# Load .env file — call this BEFORE reading any env vars
load_dotenv()
# Now all variables from .env are available via os.environ
openai_key = os.environ['OPENAI_API_KEY']
model = os.getenv('AGENT_MODEL', 'gpt-4o-mini')
max_steps = int(os.getenv('AGENT_MAX_STEPS', '20'))
print(f'Model: {model}, Max steps: {max_steps}')load_dotenv() Options
load_dotenv() has several useful options: dotenv_path= to specify a custom path, override=True to overwrite existing environment variables (default is to skip them), and verbose=True to log which file was loaded.
from dotenv import load_dotenv
import os
# Load from a specific path
load_dotenv(dotenv_path='/path/to/custom/.env')
# Override existing environment variables
# (by default, existing vars are NOT overridden)
load_dotenv(override=True)
# Load a specific environment file
env_file = os.getenv('ENV_FILE', '.env')
load_dotenv(dotenv_path=env_file, verbose=True)
# Find .env automatically (searches up the directory tree)
from dotenv import find_dotenv
load_dotenv(find_dotenv())dotenv_values() for Explicit Config Dicts
dotenv_values() returns the .env file contents as a Python dictionary without modifying the environment. This is useful when you want to inspect or use config without polluting the process environment.
from dotenv import dotenv_values
# Read .env into a dict without touching os.environ
config = dotenv_values('.env')
print(config.get('AGENT_MODEL')) # 'gpt-4o-mini'
print(config.get('LOG_LEVEL')) # 'DEBUG'
# Merge .env with actual environment (env vars take priority)
import os
combined = {**dotenv_values('.env'), **os.environ}
# This means actual environment variables override .env values
# Useful for CI where env vars are injected by the pipelineThe .env.example File
Create a .env.example file that documents all required variables with placeholder values. This file IS committed to git — it serves as documentation for teammates and new developers on what to configure.
# .env.example — commit this file to git
# Copy to .env and fill in real values:
# cp .env.example .env
# Required API keys (get from respective providers)
OPENAI_API_KEY=sk-proj-your-openai-key-here
SEARCH_API_KEY=tvly-your-tavily-key-here
# Optional settings
AGENT_MODEL=gpt-4o-mini
AGENT_MAX_STEPS=20
LOG_LEVEL=INFO
ENV=development
# Database (optional)
# DATABASE_URL=postgresql://user:password@localhost:5432/agentdbAdding .env to .gitignore
The .env file must NEVER be committed to git. Add it to .gitignore immediately when you create your project. Verify it is ignored before your first commit.
# .gitignore — add these lines
# Environment files with real secrets
.env
.env.local
.env.production
.env.staging
# But DO commit these:
# .env.example (placeholder values, safe to share)
# Verify .env is ignored before committing:
# git check-ignore -v .env
# .gitignore:1:.env .env <-- means it IS ignored (good)
# If .env was already tracked:
# git rm --cached .env
# git commit -m 'Remove .env from tracking'
# echo '.env' >> .gitignorePre-commit Hook to Block .env Commits
Add a pre-commit hook that blocks any commit containing a .env file. This provides an automatic safety net in case someone forgets to check .gitignore.
# .git/hooks/pre-commit (make executable: chmod +x .git/hooks/pre-commit)
#!/bin/sh
# Block commits that include .env files with real content
if git diff --cached --name-only | grep -qE '^\.env$';
then
echo 'ERROR: .env file is staged for commit!'
echo 'This file contains secrets and must NOT be committed.'
echo 'Run: git reset HEAD .env'
exit 1
fi
# Also check for common secret patterns in any staged file
if git diff --cached | grep -qE '(sk-proj-|tvly-|xai-)';
then
echo 'WARNING: Possible API key detected in staged changes!'
echo 'Review carefully before committing.'
fi
exit 0Loading .env in Different Frameworks
Many frameworks auto-load .env files. FastAPI (via pydantic-settings), Django (via django-environ), and Docker Compose all support .env natively. Knowing these patterns avoids duplicate loading.
# FastAPI with pydantic-settings (auto-loads .env):
# pip install pydantic-settings
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
openai_api_key: str
agent_model: str = 'gpt-4o-mini'
log_level: str = 'INFO'
class Config:
env_file = '.env'
# settings = Settings() # auto-reads .env and validates types
# print(settings.agent_model) # 'gpt-4o-mini'
# FastAPI is also fine with plain load_dotenv() at the top of main.py
# No need to use pydantic-settings for simple agentsMultiple .env Files for Environments
Use separate .env files for different environments: .env.development, .env.staging, .env.production. Load the correct one based on the ENV variable.
import os
from dotenv import load_dotenv
# Determine which environment to load
env = os.getenv('ENV', 'development')
# Try environment-specific file first, fall back to base .env
env_file = f'.env.{env}'
if os.path.exists(env_file):
load_dotenv(env_file)
print(f'Loaded {env_file}')
else:
load_dotenv('.env')
print('Loaded .env')
# Usage:
# ENV=staging python agent.py -> loads .env.staging
# ENV=production python agent.py -> loads .env.production
# python agent.py -> loads .env (default development)Full Setup Checklist
A complete .env setup checklist for a new agent project:
- Create
.envwith real keys (never commit) - Create
.env.examplewith placeholders (commit this) - Add
.envto.gitignore - Add
load_dotenv()at the top of your entry point - Validate required variables at startup
- Add
cp .env.example .envto your README setup instructions
Knowledge Check: .env Files and python-dotenv
Test your understanding of .env files and the python-dotenv library.
Recap: .env Files and python-dotenv
You now have a complete .env workflow for agent projects:
- Create a
.envfile with real values — never commit it - Create
.env.examplewith placeholders — always commit it - Add
.env*(except .env.example) to.gitignore - Call
load_dotenv()at the very top of your entry point - Use
dotenv_values()for dict access without touching os.environ - Use separate files per environment (
.env.staging,.env.production)
This workflow keeps secrets out of git while making local development easy.
Frequently asked questions
Is the “.env Files and python-dotenv” lesson free?
Yes — the full text of “.env Files and python-dotenv” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “.env Files and python-dotenv”?
Loading .env files, .gitignore rules, and dotenv best practices. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “.env Files and python-dotenv” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Environment Variables for Agents
- .env Files and python-dotenv
- Secrets Rotation and Security
- Configuration Profiles for Dev and Prod