How to Manage Environment Variables in Python | Complete Guide to Retrieving, Setting, and Deleting

1. Introduction

Python allows handling “environment variables” to dynamically configure settings within a program. Environment variables contain configuration information referenced by the system or applications during execution, such as usernames, paths, and locale settings. In this article, we will explain how to manage environment variables in Python, how to organize settings for different environments, and provide practical usage examples.

2. What Are Environment Variables?

2.1 Definition of Environment Variables

Environment variables are configuration information referenced by the operating system or applications during program execution. For example, default file paths, a user’s home directory, and language settings are stored as environment variables. Programs refer to these values to control their behavior appropriately.

2.2 Importance of Environment Variables in Python

Using environment variables in Python helps manage system-dependent settings and reduce security risks. For instance, API keys and database connection information should not be directly written in code for security reasons. By using environment variables, you can manage such sensitive information without embedding it directly in the source code.

侍エンジニア塾

3. Retrieving and Setting Environment Variables in Python

3.1 Retrieving Environment Variables

To retrieve environment variables in Python, use the os module. The os.getenv() function or os.environ.get() method allows fetching system environment variables. These functions take a specific key as an argument and return the corresponding environment variable value. If the key does not exist, they return None, ensuring safe handling in the program.

import os
print(os.getenv('HOME'))  # Retrieve the user's home directory

The os.environ object allows handling environment variables as a dictionary. You can retrieve values using os.environ['HOME'], but if the key does not exist, it raises a KeyError. Using the get() method is a more flexible approach.

import os
print(os.environ.get('HOME'))  # Retrieve the home directory without errors

3.2 Setting and Adding Environment Variables

You can set and add environment variables using os.environ. Since environment variable values are stored as strings, you need to convert numbers or lists into strings before assigning them.

import os
os.environ['NEW_VARIABLE'] = 'New Value'
print(os.environ['NEW_VARIABLE'])  # Outputs 'New Value'

Environment variables set this way are only valid during program execution and do not affect the system as a whole. If an environment variable with the same name already exists, its value will be overwritten.

4. Optimizing Application Configuration Using Environment Variables

4.1 Utilizing python-dotenv

In large projects, it is common to manage environment-specific configurations using environment variables. The python-dotenv library allows defining environment variables in a .env file and easily loading them within the project.

Example of a .env file:

DATABASE_URL=postgres://user:password@localhost:5432/dbname
SECRET_KEY=mysecretkey

You can load these variables into your program using python-dotenv as follows:

from dotenv import load_dotenv
import os

load_dotenv()  # Load the .env file
print(os.getenv('DATABASE_URL'))  # Outputs 'postgres://user:password@localhost:5432/dbname'

This approach is useful when managing different configurations for development, testing, and production environments. It enables flexible configuration management without embedding sensitive information in the source code.

RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

5. Deleting and Modifying Environment Variables

5.1 Deleting Environment Variables

To delete an environment variable, you can use the del statement or the os.environ.pop() method. The del statement completely removes the variable, while pop() retrieves and deletes the value at the same time.

import os
os.environ['TEST'] = 'testing'
del os.environ['TEST']  # Delete the 'TEST' environment variable

Here is an example using pop():

import os
os.environ['TEST'] = 'testing'
print(os.environ.pop('TEST'))  # Outputs 'testing' and removes the variable

After deletion, the environment variable can no longer be retrieved, and attempting to access it will result in an error. Handling errors for missing environment variables is an important aspect of robust programming.

6. Managing Environment Variables for Different Projects

6.1 Managing Variables for Different Environments

It is often necessary to use different settings for development, testing, and production environments. Environment variables provide an efficient way to manage these configurations. For example, you can enable debugging during development while applying enhanced security settings in production.

import os

if os.getenv('PHASE') == 'development':
    print('Running in development mode')
elif os.getenv('PHASE') == 'production':
    print('Running in production mode')

By using an environment variable like PHASE, you can execute different behaviors depending on the environment.

侍エンジニア塾

7. Practical Examples: Using Environment Variables for Language and Phase Switching

7.1 Switching Language Settings

Environment variables are also useful for language switching. The following code changes the displayed language based on the LANG environment variable.

import os

if os.getenv('LANG') == 'ja_JP.UTF-8':
    print('こんにちは!')
else:
    print('Hello!')

7.2 Switching Behavior Based on Development Phase

You can also use environment variables to switch behavior based on the development, testing, or production phase.

import os

phase = os.getenv('PHASE', 'development')

if phase == 'development':
    print('Using development phase settings')
elif phase == 'production':
    print('Using production phase settings')

By leveraging environment variables, you can flexibly adjust configurations and optimize program behavior.

8. Conclusion

Using environment variables in Python is a crucial technique for enhancing security and project flexibility. They enable developers to manage different configurations per environment and securely store sensitive information. By utilizing the os module and python-dotenv, you can build efficient and secure applications.