Course contentsShow
← Python
Lesson 720 of 1,06011. Standard Library EssentialsFree lesson

Retrieving and Modifying Environment Variables

Learners will securely access, update, and manage process-level environment variables to configure application behavior without hardcoding sensitive settings.

In this lesson, you will learn how to configure your application’s behavior dynamically by retrieving and modifying process-level environment variables.

Why use Environment Variables?

Hardcoding sensitive information like API keys, database URLs, or feature flags directly into your source code is a significant security risk and makes your application rigid. Instead, we use environment variables—key-value pairs stored by the operating system—to inject configuration settings at runtime. This allows you to swap settings (like switching from a "development" database to a "production" one) without changing a single line of code.

Interacting with the Environment

In Python, the os module provides the os.environ object, which acts as a dictionary-like interface to the process's environment variables.

To retrieve a value, you can treat os.environ like a standard dictionary:

import os

# Retrieve a specific variable
db_url = os.environ.get("DATABASE_URL", "sqlite:///default.db")
print(f"Connecting to: {db_url}")

Using .get() is a best practice because it allows you to provide a default value if the variable isn't set, preventing your program from crashing with a KeyError.

Modifying the Environment

You can also update or add variables for the current process:

# Update or set a variable
os.environ["APP_MODE"] = "production"

# Verify the change
print(os.environ["APP_MODE"])

Important Note: Changes made to os.environ only affect the current Python process and any child processes it subsequently launches. These changes are volatile; they do not persist once your script finishes executing or affect the parent shell that started your program. This makes them perfect for temporary runtime configuration without polluting your system's global settings.

When working with sensitive data like passwords or secret keys, always prefer environment variables over hardcoded strings to ensure your configuration remains decoupled from your codebase.

Key Takeaway: Use os.environ to retrieve and update configuration settings at runtime, ensuring your sensitive data remains external to your source code.