os.environ / os.getenv()
Attributes and functions from the os module for getting, setting, and checking environment variables. They are commonly used to pass sensitive information — such as database passwords and API keys — from outside the code rather than hardcoding it directly.
Syntax
import os
# Returns all environment variables as a dictionary-like object.
os.environ
# Returns the value of an environment variable (raises KeyError if not found).
os.environ['VARIABLE_NAME']
# Returns the value of an environment variable (returns a default value if not found).
os.getenv('VARIABLE_NAME', default_value)
# Sets an environment variable (affects the current process only).
os.environ['VARIABLE_NAME'] = 'value'
Attributes and Functions
| Attribute / Function | Description |
|---|---|
| os.environ | Returns the current environment variables as a dictionary-like object. You can read and modify it just like a regular dictionary. |
| os.environ['VARIABLE_NAME'] | Returns the value of the specified environment variable as a string. Raises a KeyError if the variable does not exist. |
| os.getenv('VARIABLE_NAME') | Returns the value of the specified environment variable. Returns None if the variable does not exist. |
| os.getenv('VARIABLE_NAME', default_value) | Returns the specified default value if the environment variable does not exist. |
| os.environ['VARIABLE_NAME'] = 'value' | Sets an environment variable for the current process. The value is inherited by child processes, but does not affect the shell's environment variables. |
| os.environ.get('VARIABLE_NAME', default_value) | Works like the dictionary get() method — returns the default value if the variable does not exist. |
| 'VARIABLE_NAME' in os.environ | Checks whether the specified environment variable exists. |
Sample Code
import os
# Get the value of an environment variable.
path = os.environ['PATH']
print(f'PATH: {path}')
# Use getenv() to return a default value if the variable is not set.
db_host = os.getenv('DB_HOST', 'localhost')
db_port = os.getenv('DB_PORT', '5432')
print(f'DB connection: {db_host}:{db_port}')
# Check if the variable exists before retrieving it.
if 'API_KEY' in os.environ:
api_key = os.environ['API_KEY']
print(f'API key is configured.')
else:
print('API_KEY is not set.')
# Raise an error if a required environment variable is missing.
def get_required_env(name: str) -> str:
value = os.getenv(name)
if value is None:
raise ValueError(f'Environment variable {name} is not set.')
return value
try:
secret = get_required_env('SECRET_KEY')
except ValueError as e:
print(e)
# Set an environment variable (valid for the current process only).
os.environ['MY_APP_DEBUG'] = 'true'
print(os.getenv('MY_APP_DEBUG')) # Prints 'true'.
# List all environment variables.
for key, value in os.environ.items():
print(f'{key}={value}')
Notes
Environment variables are a mechanism for controlling program behavior from outside the code. They let you manage database connection details, API keys, and environment flags (such as switching between production and development) without hardcoding them.
For managing environment variables in production, the python-dotenv library is a popular choice. A common pattern is to define variables in a .env file at the project root and load them with load_dotenv().
Always add any .env file containing sensitive information — such as API keys or passwords — to .gitignore to keep it out of version control. Accidentally committing it to a repository can lead to a data breach.
For reading command-line arguments and system information, see 'sys.argv / sys.exit() / sys.path'.
If you find any errors or copyright issues, please contact us.