os.environ / os.getenv()
| Since: | Python 2(2000) |
|---|
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
os_environ_basic.py
import os
path = os.environ['PATH']
print(f'PATH: {path}')
db_host = os.getenv('DB_HOST', 'localhost')
db_port = os.getenv('DB_PORT', '5432')
print(f'DB connection: {db_host}:{db_port}')
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.')
Running the code produces the following output:
python3 os_environ_basic.py PATH: /usr/local/bin:/usr/bin:/bin DB connection: localhost:5432 API_KEY is not set.
os_environ_required.py
import os
def get_required_env(name):
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')
print(f'SECRET_KEY: {secret}')
except ValueError as e:
print(e)
os.environ['MY_APP_DEBUG'] = 'true'
print(os.getenv('MY_APP_DEBUG'))
Running the code produces the following output:
python3 os_environ_required.py Environment variable SECRET_KEY is not set. true
os_environ_list.py
import os
for key, value in os.environ.items():
print(f'{key}={value}')
Running the code produces the following output:
python3 os_environ_list.py TERM=xterm-256color SHELL=/bin/zsh HOME=/Users/user PATH=/usr/local/bin:/usr/bin:/bin ...
Common Mistakes
Common Mistake 1: Accessing a missing variable with os.environ[]
os.environ['VARIABLE_NAME'] raises a KeyError when the variable does not exist. For variables that may not be set, using os.getenv() avoids the KeyError.
import os api_key = os.environ['API_KEY'] print(api_key)
The same logic can also be written as:
import os
api_key = os.getenv('API_KEY', 'default_key')
print(api_key)
Common Mistake 2: Committing a .env file to Git
Including a .env file containing sensitive information such as API keys or passwords in a Git repository can lead to a data breach. Adding it to .gitignore keeps it out of version control.
requirements.txt
The same logic can also be written as:
.env requirements.txt
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.