Use os.getenv("VAR_NAME") or os.environ.get("VAR_NAME") from Python’s built-in os module to read environment variables safely without raising an error if the variable is missing, or os.environ["VAR_NAME"] when a missing variable should fail immediately with a KeyError.

Basic Example

import os

# 1. Safe access: returns None if "API_KEY" is not set
api_key = os.getenv("API_KEY")

# 2. Safe access with a fallback default value
env_mode = os.getenv("APP_ENV", "production")

# 3. Strict access: raises KeyError immediately if "SECRET_TOKEN" is missing
# secret_token = os.environ["SECRET_TOKEN"]

print(f"Environment: {env_mode}")  # Output: Environment: production

Key Details & Common Patterns

  • Environment variables are always strings (str): Even if an environment variable is set to 8080 or True in your shell, os.getenv() returns "8080" or "True" as a str. Always cast numeric or boolean values explicitly:
    port = int(os.getenv("PORT", "8000"))
    debug = os.getenv("DEBUG", "false").lower() in ("true", "1", "yes")
    
  • Empty string vs. unset variable: If a variable is defined in the shell as export API_KEY="", os.getenv("API_KEY", "default") returns "" (not "default") because the key exists in os.environ. Use os.getenv("API_KEY") or "default" if you want empty strings to also trigger the fallback.
  • Loading variables from a .env file (python-dotenv): Python does not automatically read .env files into os.environ. For local development, install python-dotenv (pip install python-dotenv) and call load_dotenv() at startup:
    from dotenv import load_dotenv
    import os
    
    load_dotenv()  # Loads key=value pairs from .env into os.environ
    db_url = os.getenv("DATABASE_URL")
    
  • Listing all available environment variables: os.environ behaves like a standard Python dictionary (Mapping), so you can inspect all active variables with dict(os.environ) or check membership via "PATH" in os.environ.

Comparison of Access Methods

Method Missing Variable Behavior Supports Default Value? Best Used When
os.getenv("KEY", default) Returns default (None if omitted) Yes Optional settings, feature flags, and fallback configurations.
os.environ.get("KEY", default) Returns default (None if omitted) Yes Identical to os.getenv(); useful when chaining dict methods.
os.environ["KEY"] Raises KeyError No Mandatory secrets/credentials where the app must fail fast at startup.