Lesson 4 of 20

Environment Setup

Environment Variables

2 min read

Environment variables store configuration values outside your code. This is crucial for AI development where you'll work with API keys that must stay secret.

Why Not Hardcode Keys?

# NEVER do this!
client = OpenAI(api_key="sk-abc123...")  # Exposed in code!

If you commit this to git, your key is compromised. Environment variables solve this.

Using .env Files

The python-dotenv package loads variables from a .env file.

Installation

pip install python-dotenv

Create .env File

# .env file (in your project root)
OPENAI_API_KEY=sk-your-key-here
ANTHROPIC_API_KEY=sk-ant-your-key-here
DEBUG=true

Load in Python

from dotenv import load_dotenv
import os

# Load variables from .env file
load_dotenv()

# Access variables
api_key = os.getenv("OPENAI_API_KEY")
debug = os.getenv("DEBUG", "false")  # "false" is the default

Security Best Practices

1. Add .env to .gitignore

# .gitignore
.env
.env.local
*.env

2. Create a Template

Share a .env.example file without real values:

# .env.example
OPENAI_API_KEY=your-key-here
ANTHROPIC_API_KEY=your-key-here

3. Validate Required Variables

import os
import sys

required_vars = ["OPENAI_API_KEY"]

for var in required_vars:
    if not os.getenv(var):
        print(f"Error: {var} not set")
        sys.exit(1)

Quick Reference

Task Command
Install dotenv pip install python-dotenv
Load .env load_dotenv()
Get variable os.getenv("KEY")
Get with default os.getenv("KEY", "default")

You've completed the Environment Setup module! Next, we'll dive into Python data structures. :::

Quiz

Module 1: Environment Setup

Take Quiz