How to Read Environment Variables in Python with Default Values

Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 11 views 0 copies

Python code

4 lines
Python 3.9+
import os

database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")

Output

stdout
Database URL: postgresql://localhost:5432/mydb

How it works

os.getenv() returns the value of the named environment variable or the default if it is not set. It never raises an error when the variable is missing, making it ideal for configuration that may vary between environments. Using a default helps your code run without requiring every variable to be present, which simplifies local development and CI. This function is part of Python's standard os module, so no installation is needed.

Common mistakes

  • Forgetting to pass a default and getting None when the variable is missing, causing unexpected errors later.
  • Using `os.environ` directly without `.get()` and hitting a KeyError on missing variables.

Variations

  1. Use `os.environ.get("DATABASE_URL")` for a more explicit expression of the dictionary-like access.
  2. Set a default with `os.getenv("DATABASE_URL", "")` to treat an empty string as the fallback.

Real-world use cases

  • Pulling database connection strings from environment variables in a Django or Flask app so credentials are not hard-coded.
  • Reading API keys for third‑party services (like AWS or Stripe) in a script that runs in different environments.
  • Loading deployment-specific configuration, such as feature flags or port numbers, without changing source code.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.