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.
Python code
4 linesimport os
database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
Output
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
- Use `os.environ.get("DATABASE_URL")` for a more explicit expression of the dictionary-like access.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.