Skip to content

Lesson 07 – Environment Variables and .env Files

Prerequisites: Make sure you've reviewed Lesson 01 – Markdown Fundamentals so you can clearly document the variables your project requires.

Environment variables store configuration outside your code so you can keep secrets and machine-specific settings separate from the application logic. A .env file helps manage these variables locally.

1. Why Use a .env File?

  • Security: Keep API keys and passwords out of your repository.
  • Flexibility: Change settings for different environments (development, staging, production) without editing code.
  • Convenience: Load variables automatically when your application starts.
flowchart TD
    A[Application startup] --> B(Read .env file)
    B --> C{Environment variables}
    C --> D[Use in code]

2. Creating the File

  1. In your project root, create a file named .env.
  2. Add key/value pairs in the format NAME=value:
    DATABASE_URL=postgresql://user:pass@localhost:5432/appdb
    SECRET_KEY=mysecret
    
  3. Never commit this file to version control. Add .env to your .gitignore.

3. Loading Variables in Python

Use the python-dotenv package to load values from .env:

pip install python-dotenv
from dotenv import load_dotenv
import os

load_dotenv()  # reads variables from .env
DATABASE_URL = os.getenv("DATABASE_URL")
SECRET_KEY = os.getenv("SECRET_KEY")

4. Best Practices

  • Store non-sensitive defaults in code and override with environment variables when needed.
  • Use separate .env files for different stages (e.g., .env.dev, .env.prod).
  • Document required variables in a README or sample file like .env.example.

Using a .env file keeps configuration simple and secure across projects. Remember to keep sensitive values out of your repository and load them at runtime.

Next Up

Explore how Python packages are structured in Lesson 08 – Understanding __init__.py to organize your growing codebase.