Back to Blog
June 12, 2024 6 min read

Reading Environment Variables in Python

Python DevOps

Reading Environment Variables in Python

When developing applications, it is a best practice to keep sensitive information—such as API keys, database credentials, and configuration settings—out of your source code. Hardcoding these values makes your code less secure and harder to manage across different environments (development, staging, production).

Environment variables provide a clean solution to this problem. In Python, reading these variables is straightforward using the built-in os module or third-party libraries like python-dotenv.

1. Using the os Module

The simplest way to access environment variables is through the os.environ dictionary.

import os

# Accessing a variable directly
# Note: This will raise a KeyError if the variable does not exist
db_user = os.environ['DATABASE_USER']

# Using .get() for safer access
# This returns None (or a default value) if the variable is missing
api_key = os.environ.get('API_KEY')
debug_mode = os.environ.get('DEBUG', 'False')

2. Managing Local Environments with .env Files

For local development, it is common to store variables in a file named .env in your project root. This file should never be committed to version control (add it to your .gitignore).

Example .env file:

DATABASE_URL=postgres://user:password@localhost:5432/mydb
SECRET_KEY=your-super-secret-key
DEBUG=True

3. Using python-dotenv

To automatically load these variables into your environment when your script runs, use the python-dotenv library.

Installation:

pip install python-dotenv

Usage:

import os
from dotenv import load_dotenv

# Load variables from .env into the environment
load_dotenv()

# Now you can access them as if they were system environment variables
db_url = os.getenv('DATABASE_URL')
secret_key = os.getenv('SECRET_KEY')

print(f"Connecting to: {db_url}")

Why This Matters

  1. Security: Prevents accidental leaks of credentials in public repositories.
  2. Portability: Allows the same code to run in different environments by simply changing the environment variables.
  3. Compliance: Follows the "Twelve-Factor App" methodology for building modern, scalable applications.

Thanks for reading!

I hope you found this technical dive useful. Feel free to connect with me if you have any questions or thoughts.

Connect with me
© 2026 Adam Lamers
Framework: Svelte_5
Runtime: Cloudflare