Environment variables

suggest change

Environment variables provide a standard way to configure applications across different environments (development, staging, production) without hardcoding secrets, credentials, API URLs, or port numbers in source code.

In Python, the built-in os module provides access to process environment variables via os.environ and os.getenv(). For managing .env files, third-party libraries such as python-dotenv are commonly used.


1. Reading Environment Variables

Using os.getenv()

os.getenv(key, default=None) is the safest way to read a single environment variable:

import os

# Returns None if the variable is not set
api_key = os.getenv("API_KEY")

# Provide a fallback default value
port = os.getenv("PORT", "8080")
debug_mode = os.getenv("DEBUG", "false").lower() in ("true", "1", "yes")

print(f"Port: {port}, Debug: {debug_mode}")

Using os.environ

os.environ behaves like a Python mapping (dictionary) of all environment variables:

import os

# Subscript access raises KeyError if the variable is not found
try:
    secret_key = os.environ["SECRET_KEY"]
except KeyError:
    print("Error: SECRET_KEY environment variable is required!")

# Dictionary .get() method with optional default
database_url = os.environ.get("DATABASE_URL", "sqlite:///app.db")

Tip: Use os.environ[key] when a missing variable is a fatal configuration error that should fail immediately on startup. Use os.getenv(key, default) when a sensible default exists.


2. Setting and Modifying Environment Variables

You can assign values to os.environ to modify the environment of the current Python process and any child processes it spawns (e.g., via subprocess):

import os

# Values MUST be strings
os.environ["APP_ENV"] = "production"
os.environ["MAX_CONNECTIONS"] = str(100)

print(os.environ["APP_ENV"])  # => production

Important: Changes made to os.environ only affect the current process and subprocesses created after the modification. They do not affect the parent shell or other running processes on the system.


3. Deleting Environment Variables

Remove variables using del or .pop():

import os

# Using del (raises KeyError if not present)
if "TEMP_TOKEN" in os.environ:
    del os.environ["TEMP_TOKEN"]

# Using pop with a default (safe, does not raise KeyError)
old_value = os.environ.pop("OLD_CONFIG", None)

4. Type Conversion and Parsing

All environment variables are stored and retrieved as strings. When working with numbers, booleans, or lists, you must explicitly parse them:

import os

# Integer conversion with fallback
try:
    worker_threads = int(os.getenv("WORKER_THREADS", "4"))
except ValueError:
    worker_threads = 4

# Boolean parsing helper
def parse_bool(env_var: str, default: bool = False) -> bool:
    val = os.getenv(env_var)
    if val is None:
        return default
    return val.strip().lower() in ("1", "true", "yes", "on")

is_production = parse_bool("PRODUCTION", default=False)

# List / comma-separated string
allowed_hosts = [
    host.strip()
    for host in os.getenv("ALLOWED_HOSTS", "localhost,127.0.0.1").split(",")
    if host.strip()
]

5. Iterating and Filtering Environment Variables

Because os.environ is a mapping, you can iterate over keys, values, or filter for specific prefixes:

import os

# Print all AWS-related environment variables
for key, value in sorted(os.environ.items()):
    if key.startswith("AWS_"):
        # Mask sensitive keys
        masked = "***" if "SECRET" in key or "KEY" in key else value
        print(f"{key}={masked}")

6. Loading from .env Files (python-dotenv)

During local development, environment variables are typically defined in a .env file in the project root:

# .env
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
DEBUG=true
PORT=5000

Install python-dotenv:

pip install python-dotenv

Load the file at application entry:

import os
from dotenv import load_dotenv

# Load variables from .env into os.environ
# By default, existing environment variables are NOT overridden
load_dotenv()

db_url = os.getenv("DATABASE_URL")
debug = os.getenv("DEBUG")

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

To allow .env values to overwrite existing environment variables:

load_dotenv(override=True)

7. Structured Settings with pydantic-settings

For larger applications, pydantic-settings provides automatic type validation and reading from environment variables:

pip install pydantic-settings
from pydantic_settings import BaseSettings, SettingsConfigDict

class AppConfig(BaseSettings):
    app_name: str = "MyService"
    port: int = 8080
    debug: bool = False
    database_url: str

    model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")

# Automatically reads DATABASE_URL, PORT, etc., validates types, and assigns defaults
config = AppConfig()

print(config.app_name)
print(config.port)         # Automatically cast to int
print(config.debug)        # Automatically cast to bool

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents