Using environment variables in Python is a common practice to manage configuration settings, sensitive data, and other information that should not be hardcoded into your scripts. Here's how you can work with environment variables in Python:

1. Setting Environment Variables

Environment variables can be set in your operating system or within your code.

On Windows:

set MY_VARIABLE=some_value

On macOS/Linux:

export MY_VARIABLE=some_value

2. Accessing Environment Variables in Python

In Python, you can access environment variables using the os module. Here’s a simple example:

import os

# Access an environment variable
my_var = os.getenv('MY_VARIABLE')

# Print the value of the environment variable
print(f'MY_VARIABLE: {my_var}')
  • os.getenv('VAR_NAME'): This method returns the value of the environment variable VAR_NAME. If the variable does not exist, it returns None.
  • os.environ['VAR_NAME']: This is another way to access environment variables, but it raises a KeyError if the variable is not found.

3. Setting Environment Variables in Python

You can also set environment variables within your Python script:

import os

# Set an environment variable
os.environ['NEW_VARIABLE'] = 'new_value'

# Access the newly set environment variable
print(os.getenv('NEW_VARIABLE'))

4. Using Environment Variables for Configuration

Environment variables are often used to store configuration settings, such as database credentials or API keys, in a secure and flexible way. This allows you to avoid hardcoding sensitive information directly into your scripts.

import os

# Example: Accessing sensitive information
db_username = os.getenv('DB_USERNAME')
db_password = os.getenv('DB_PASSWORD')

# Using the credentials
print(f'Connecting to the database with username {db_username}')

5. Using .env Files

A common practice is to store environment variables in a .env file and load them using a package like python-dotenv:

Step 1: Install the package

pip install python-dotenv

Step 2: Create a .env file

DB_USERNAME=my_username
DB_PASSWORD=my_password

Step 3: Load the .env file in your Python script

from dotenv import load_dotenv
import os

# Load the .env file
load_dotenv()

# Access the variables
db_username = os.getenv('DB_USERNAME')
db_password = os.getenv('DB_PASSWORD')

print(f'DB_USERNAME: {db_username}')

6. Security Considerations

When using environment variables, especially for sensitive data, it's crucial to keep .env files out of version control by adding them to your .gitignore file.

# .gitignore
.env

Using environment variables in Python is a simple yet powerful way to manage configurations and sensitive data securely and flexibly.

Simon

102 Articles

I love talking about tech.