Python22 min read

Python Environment Variables

Store configuration safely using environment variables so you can keep secrets out of code, run the same app in dev and production, and deploy with confidence.

David Miller
September 3, 2025
7.7k371

Environment variables are settings stored outside your code.

        Examples:
        - DB_HOST
        - API_KEY
        - SECRET_KEY
        - DEBUG mode
        
        ### Why they matter
        If you hardcode secrets in code:
        - they can leak in GitHub
        - they are hard to change per environment
        - your app becomes unsafe
        
        Environment variables solve that.
        
        ## Read environment variables
        
        ```python
        import os
        
        db_host = os.environ.get("DB_HOST", "localhost")
        db_port = os.environ.get("DB_PORT", "5432")
        
        print(f"Connecting to {db_host}:{db_port}")
        ```
        
        ## Setting environment variables (concept)
        
        You typically set env vars in:
        - terminal
        - Docker
        - CI/CD pipeline
        - server environment
        
        Example (Linux/macOS):
        ```bash
        export DB_HOST=localhost
        ```
        
        Example (Windows PowerShell):
        ```powershell
        $env:DB_HOST="localhost"
        ```
        
        ## Using .env file (common in development)
        
        ```bash
        pip install python-dotenv
        ```
        
        Create `.env`:
        ```
        DB_HOST=localhost
        DB_PORT=5432
        API_KEY=secret123
        ```
        
        Load it:
        ```python
        from dotenv import load_dotenv
        import os
        
        load_dotenv()
        
        db_host = os.getenv("DB_HOST")
        api_key = os.getenv("API_KEY")
        print(db_host)
        ```
        
        ## Config class pattern (clean and organized)
        
        ```python
        import os
        from dotenv import load_dotenv
        
        load_dotenv()
        
        class Config:
            DB_HOST = os.getenv("DB_HOST", "localhost")
            DB_PORT = int(os.getenv("DB_PORT", "5432"))
            API_KEY = os.getenv("API_KEY")
            DEBUG = os.getenv("DEBUG", "False").lower() == "true"
        
        config = Config()
        print(config.DB_HOST, config.DB_PORT)
        ```
        
        ## Graph: config flow
        
        ```mermaid
        flowchart LR
          A[.env / server env vars] --> B[os.getenv]
          B --> C[Config class]
          C --> D[App uses settings safely]
        ```
        
        ## Remember
        
        - Never commit .env files to Git
        - Keep secrets in env vars
        - Use defaults for non-secret config
        - Different env vars for dev vs production
        
#Python#Advanced#Configuration