Python
Coding
Environment Variables
Programming
Python Tutorial

How to set environment variables in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Environment variables are a set of dynamic values that can affect the way running processes behave on a computer. They are often used to manage system paths, configuration settings, and other variables that should not be hardcoded in a program, especially sensitive data such as API keys, database credentials, or configuration options. Python provides several ways to access and set these environment variables.

Understanding Environment Variables in Python

Python interacts with environment variables using the os module. The os module has os.environ which is a dictionary representing the user’s environmental variables. It allows read and write operations, behaving much like a standard Python dictionary.

Reading Environment Variables

To access an environment variable in Python, you can use the os.environ dictionary. For example, to get the value of the user's HOME directory, you can use the following code:

python
1import os
2
3home_directory = os.environ.get('HOME')
4print(home_directory)

If the environment variable does not exist, os.environ.get('KEY') will return None. This method is safer than using os.environ['KEY'], which raises a KeyError if the key is not found.

Setting Environment Variables

You can also set environment variables using os.environ. It's important to note that these changes affect only the current process where the script is run and child processes spawned after the setting.

Here’s an example of how to set an environment variable:

python
1import os
2
3# Setting an environment variable
4os.environ['MY_VAR'] = 'some_value'
5
6# Accessing the environment variable
7print(os.environ.get('MY_VAR'))

Using os.environb for Bytes

If you need to work with environment variables in a bytes format, Python’s os module also provides os.environb which is just like os.environ, but keys and values are expected to be bytes.

Removing Environment Variables

Environment variables can be removed using the del keyword or the pop method:

python
1import os
2
3# Removing an environment variable using del
4del os.environ['MY_VAR']
5
6# Removing an environment variable using pop
7os.environ.pop('MY_VAR', None)  # None is returned if MY_VAR does not exist

Persisting Environment Variables

Changes made with os.environ are temporary and only affect the current process. To make persistent changes, you need to use platform-dependent tools:

  • On Linux & MacOS: Set variables in files like ~/.bashrc or ~/.profile.
  • On Windows: Use the Control Panel or the setx command in the command line.

Using Python-dotenv

For applications, particularly those following the twelve-factor app methodology, using .env files to load configuration is popular. Python-dotenv is a package that reads key-value pairs from a .env file and sets them as environment variables.

First, install the package:

bash
pip install python-dotenv

Then, suppose you have a .env file:

 
API_KEY=your-api-key

Use python-dotenv to load these values:

python
1from dotenv import load_dotenv
2import os
3
4load_dotenv()  # Take environment variables from .env.
5
6api_key = os.environ.get('API_KEY')
7print(api_key)

Table of Key Functions and Usage

FunctionDescription
os.environAccess environment as a dictionary-like object.
os.environ.get('KEY')Safely get an environment variable, returns None if not found.
os.environ['KEY'] = 'value'Set an environment variable for the current process.
del os.environ['KEY']Remove an environment variable from the current process.
load_dotenv()Load environment variables from a .env file.

Summary

Environment variables are a crucial part of developing applications that interact with different system environments and third-party services without hardcoding sensitive information. Python's os module provides a straightforward interface to manage these variables effectively, enhancing security and flexibility in application configuration.


Course illustration
Course illustration

All Rights Reserved.