Environment Variables

Advanced PythonConfigurationFree Lesson

Advertisement

Introduction

Managing configuration through environment variables for different environments.

Reading Variables

import os

# Basic reading
db_host = os.getenv("DB_HOST", "localhost")
db_port = os.getenv("DB_PORT", "5432")

# With type conversion
timeout = int(os.getenv("TIMEOUT", "30"))

# Required variables
api_key = os.environ["API_KEY"]  # Raises KeyError if missing

dotenv

# pip install python-dotenv
from dotenv import load_dotenv

load_dotenv()  # Load .env file

# Now os.getenv works with .env values
api_key = os.getenv("API_KEY")

.env File Format

DATABASE_URL=postgres://user:pass@localhost/db
API_KEY=abc123xyz
DEBUG=true
LOG_LEVEL=INFO

Practice Problems

  1. Load config from environment
  2. Create .env template
  3. Validate required variables
  4. Support multiple environments
  5. Use pydantic-settings for config

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement