← Master Index
Vol. 03 Module 3.4 Lecture

Environment Variables (.env)

Essential Python Skills for AI Engineers (added — needed in practice, not in original outline)

How This Lesson Fits the Module

Hard-coding API keys in source files is a security incident waiting to happen. Environment variables store configuration outside code—database URLs, model endpoints, API keys—and differ per machine (laptop vs staging vs production). The .env file plus python-dotenv is the standard local-development pattern before you adopt Docker secrets or cloud parameter stores in later volumes.

This lecture pairs directly with Calling REST APIs: load secrets first, then call external services.

Learning Objectives

By the end of this lesson, students should be able to:

  • Read environment variables with os.environ and os.getenv().
  • Load a .env file using python-dotenv.
  • Explain why secrets must not be committed to version control.
  • Provide defaults and fail fast when required variables are missing.
  • Separate config (env) from code (logic) following 12-factor app principles.
  • Recognize production alternatives: AWS Secrets Manager, Azure Key Vault, Doppler.

Introduction: Configuration Outside Code

An environment variable is a key–value pair set in the operating system process environment. Your Python process inherits these values at startup. Deployment platforms inject different values per environment without changing source code.

# .env (never commit to git)
OPENAI_API_KEY=sk-...
DATABASE_URL=postgresql://localhost:5432/rag
MODEL_NAME=gpt-4o-mini
LOG_LEVEL=INFO
import os
from dotenv import load_dotenv

load_dotenv()  # reads .env into os.environ

api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise RuntimeError("OPENAI_API_KEY is not set")

model = os.getenv("MODEL_NAME", "gpt-4o-mini")  # default if missing
Definition — 12-Factor Config

Store config in the environment, not in code. Strict separation keeps the same codebase deployable to dev, staging, and production with different credentials and endpoints.

VariableExample Use in AI
OPENAI_API_KEYLLM provider authentication
DATABASE_URLVector store / metadata DB connection
MODEL_NAMESwitch models without code changes
LOG_LEVELControl verbosity in production
Common Misconception:.env files are safe to share in Slack or commit privately.”

Reality: Treat every secret as compromised once exposed. Add .env to .gitignore, rotate keys immediately if leaked, and use .env.example (without real values) to document required variables.

.env.example Pattern

# .env.example (committed — documents required keys)
OPENAI_API_KEY=your-key-here
DATABASE_URL=postgresql://user:pass@host:5432/db
MODEL_NAME=gpt-4o-mini

Knowledge Check

  1. Short Answer: Which function loads .env into Python? Answer: load_dotenv() from python-dotenv.
  2. True/False: os.getenv("KEY", "default") returns "default" if KEY is unset. Answer: True.
  3. Multiple Choice: Where should production secrets ultimately live? (a) GitHub repo, (b) secret manager / platform env, (c) README, (d) Jupyter output. Answer: (b).
  4. Short Answer: How do you read an env var without a default? Answer: os.environ["KEY"] or os.getenv("KEY").
  5. True/False: Commit .env to git so teammates share real API keys. Answer: False—gitignore .env; commit .env.example with placeholders.
  6. Short Answer: What should you do if a required key is missing? Answer: Fail fast (e.g. raise RuntimeError) rather than continue silently.
  7. Multiple Choice: 12-factor config stores settings: (a) in source constants, (b) in the environment, (c) only in Slack, (d) inside model weights. Answer: (b).
  8. True/False: MODEL_NAME can switch models without changing code. Answer: True.
  9. Short Answer: Name one production secret store alternative to local .env. Answer: AWS Secrets Manager, Azure Key Vault, or Doppler (any one).
  10. Multiple Choice: If a secret leaks, you should: (a) ignore it, (b) rotate the key immediately, (c) print it in notebooks, (d) email it again. Answer: (b).

Key Takeaways

  • Never hard-code API keys; use environment variables.
  • python-dotenv loads local .env files for development.
  • Commit .env.example, gitignore .env.
  • Next: Type Hints for clearer, more maintainable AI codebases.
Trainer’s Guide

Security drill: Show a git history leak scenario. Students add .env to .gitignore and create .env.example with placeholder values.

Recap: Keep secrets in the environment, not in code; next, document intent with Type Hints.