Skip to content

Instantly share code, notes, and snippets.

@fahim-muntasir-niloy
Last active July 31, 2025 09:27
Show Gist options
  • Select an option

  • Save fahim-muntasir-niloy/138fa689a432a910d879488548025ee8 to your computer and use it in GitHub Desktop.

Select an option

Save fahim-muntasir-niloy/138fa689a432a910d879488548025ee8 to your computer and use it in GitHub Desktop.
Environment-Based Configuration for Python Projects

🌐 Environment-Based Configuration for Python Projects

This guide explains how to manage different environments (development, staging, production) using .env files and Python's dotenv.


βœ… Project Structure

project-root/
β”œβ”€β”€ .env                 # Optional: base ENV loader
β”œβ”€β”€ .env.dev             # Development environment variables
β”œβ”€β”€ .env.stage           # Staging environment variables
β”œβ”€β”€ .env.prod            # Production environment variables
β”œβ”€β”€ load\_env.py          # Environment loader script
└── main.py              # Your app entry point

πŸ“œ load_env.py

import os
from dotenv import load_dotenv

# Load base .env (optional) to fetch ENV variable
load_dotenv(".env")

# Get current ENV type
env_type = os.getenv("ENV", "development")
print("ENV from system:", env_type)

# Map ENV to corresponding .env file
env_file = {
    "development": ".env.dev",
    "stage": ".env.stage",
    "production": ".env.prod",
}.get(env_type)

if env_file is None:
    raise ValueError("Unknown ENV value. Must be one of: development, stage, production.")

print(f"Using environment file: {env_file}")

# Load the appropriate environment file
load_dotenv(dotenv_path=env_file, override=True)

πŸ“„ Environment Files

.env.dev

ENV=development
DB_NAME=dev_ai_db
DB_USERNAME=dev_ai_user
DB_PASSWORD=dev_password
DB_HOST=localhost
DB_PORT=5432

.env.stage

ENV=stage
DB_NAME=stage_ai_db
DB_USERNAME=stage_ai_user
DB_PASSWORD=stage_password
DB_HOST=staging-db.example.com
DB_PORT=5432

.env.prod

ENV=production
DB_NAME=ai_db
DB_USERNAME=ai_user
DB_PASSWORD=prod_password
DB_HOST=prod-db.example.com
DB_PORT=5432

πŸš€ How to Run

PowerShell / VSCode Terminal (Windows)

$env:ENV="stage"; python main.py

CMD (Classic Command Prompt)

set ENV=stage && python main.py

Alternative: Use .env for ENV value

Set ENV=stage in a .env file:

ENV=stage

Then run:

python main.py

πŸ›‘ Best Practices

  • ❌ Never commit .env.prod to version control.
  • βœ… Use .env + load_env.py for safer config switching.
  • βœ… Use override=True in load_dotenv to avoid conflict.
  • βœ… Confirm loaded file with a print() for debugging.

Happy coding! πŸ§ βš™οΈ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment