Question
How can I get the value of an environment variable in Python?
Short Answer
By the end of this page, you will understand how Python reads environment variables, how to safely access them with os.environ and os.getenv, what happens when a variable is missing, and how this is commonly used in real applications for configuration, secrets, and deployment settings.
Concept
Environment variables are key-value pairs provided by the operating system to a running program. In Python, they are commonly used to pass configuration into an application without hardcoding values directly in the source code.
This matters because real programs often need values that change between environments, such as:
- database URLs
- API keys
- debug flags
- file paths
- port numbers
Python provides access to environment variables through the os module.
Two common ways to read them are:
os.environ["NAME"]os.getenv("NAME")
They look similar, but they behave differently when the variable does not exist:
os.environ["NAME"]raises aKeyErroros.getenv("NAME")returnsNoneby default, or a fallback value if you provide one
Using environment variables helps keep code portable and secure. For example, you should usually store secrets like API tokens in environment variables instead of committing them into your codebase.
Mental Model
Think of environment variables like labeled sticky notes attached to your program when it starts.
Each sticky note has:
- a name, such as
DATABASE_URL - a value, such as
postgres://localhost:5432/app
Your Python program can read those notes while it runs.
os.environ["DATABASE_URL"]means: "Give me the note with this exact name, and fail if it is missing."os.getenv("DATABASE_URL")means: "Give me the note if it exists, otherwise give me nothing or a default value."
This is useful because the same program can behave differently depending on which notes the operating system provides.
Syntax and Examples
The os module gives access to environment variables.
Basic syntax
import os
value = os.environ["VARIABLE_NAME"]
import os
value = os.getenv("VARIABLE_NAME")
import os
value = os.getenv("VARIABLE_NAME", "default_value")
Example: read an environment variable
import os
username = os.getenv("USERNAME")
print(username)
This tries to read the USERNAME environment variable.
- If it exists, its value is returned.
- If it does not exist,
Noneis returned.
Example: provide a default value
import os
mode = os.getenv("APP_MODE", "development")
print(mode)
If is not set, Python uses .
Step by Step Execution
Consider this example:
import os
port = os.getenv("PORT", "8000")
print(port)
Step by step
- Python imports the
osmodule. os.getenv("PORT", "8000")checks whether the environment contains a variable namedPORT.- If
PORTexists, its value is returned. - If
PORTdoes not exist, the default value"8000"is returned. - The result is stored in
port. print(port)outputs the final value.
Example outcomes
If the environment contains:
PORT=5000
then the output is:
5000
If PORT is not set, the output is:
8000
Real World Use Cases
Environment variables are widely used in real software.
Application configuration
import os
debug = os.getenv("DEBUG", "false")
A web app may enable or disable debug mode based on deployment settings.
Database connections
import os
database_url = os.getenv("DATABASE_URL")
Applications often read connection strings this way so development, staging, and production can use different databases.
API credentials
import os
api_token = os.getenv("API_TOKEN")
Secrets should usually come from the environment instead of being hardcoded.
Server port selection
import os
port = int(os.getenv("PORT", "8000"))
Platforms like cloud hosting services often provide the port through an environment variable.
File and path settings
import os
log_dir = os.getenv("LOG_DIR", )
Real Codebase Usage
In real projects, developers rarely read environment variables randomly throughout the codebase. Instead, they usually centralize configuration.
Common pattern: configuration section
import os
class Config:
DEBUG = os.getenv("DEBUG", "false").lower() == "true"
PORT = int(os.getenv("PORT", "8000"))
DATABASE_URL = os.getenv("DATABASE_URL")
This keeps configuration in one place.
Guard clause for required settings
import os
database_url = os.getenv("DATABASE_URL")
if not database_url:
raise RuntimeError("DATABASE_URL is required")
This fails early instead of causing confusing errors later.
Validation and conversion
import os
raw_timeout = os.getenv("TIMEOUT", "30")
timeout = int(raw_timeout)
Since environment variables are strings, developers often convert them into int, float, or .
Common Mistakes
1. Forgetting to import os
Broken code:
value = os.getenv("HOME")
Problem:
osis not defined.
Fix:
import os
value = os.getenv("HOME")
2. Using os.environ[...] when the variable might be missing
Broken code:
import os
mode = os.environ["APP_MODE"]
Problem:
- This raises
KeyErrorifAPP_MODEis not set.
Fix:
import os
mode = os.getenv("APP_MODE", "development")
3. Forgetting that values are strings
Broken code:
os
port = os.getenv(, )
(port + )
Comparisons
| Approach | Missing variable behavior | Best use case | Example |
|---|---|---|---|
os.environ["NAME"] | Raises KeyError | Required variables | os.environ["API_KEY"] |
os.getenv("NAME") | Returns None | Optional variables | os.getenv("LOG_LEVEL") |
os.getenv("NAME", "default") | Returns default value | Optional variables with fallback | os.getenv("PORT", "8000") |
os.environ vs os.getenv
Cheat Sheet
import os
Read a required variable
value = os.environ["NAME"]
- Raises
KeyErrorif missing
Read an optional variable
value = os.getenv("NAME")
- Returns
Noneif missing
Read with a default
value = os.getenv("NAME", "default")
Convert to integer
port = int(os.getenv("PORT", "8000"))
Convert to boolean safely
debug = os.getenv("DEBUG", "false").lower() == "true"
Check for required variable manually
api_key = os.getenv()
api_key :
ValueError()
FAQ
How do I read an environment variable in Python?
Use the os module:
import os
value = os.getenv("MY_VAR")
What is the difference between os.getenv() and os.environ[]?
os.getenv() returns None or a default value if the variable is missing. os.environ[] raises KeyError if it is missing.
How do I provide a default value for an environment variable in Python?
Pass a second argument to os.getenv():
port = os.getenv("PORT", "8000")
Why is my environment variable a string even when it looks like a number?
Environment variables are stored as text. Convert them explicitly:
timeout = int(os.getenv("TIMEOUT", "30"))
How do I check if an environment variable exists in Python?
Mini Project
Description
Build a small Python configuration loader for a script. This project demonstrates how to read required and optional environment variables, apply defaults, and convert string values into useful Python types.
Goal
Create a Python script that loads app settings from environment variables and prints the final configuration safely.
Requirements
Requirement 1 Requirement 2 Requirement 3
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.