DEV Community

Cover image for Access Environment Variables in Python: Set, Get, Read
Hichem MG
Hichem MG

Posted on

Access Environment Variables in Python: Set, Get, Read

Environment variables are a fundamental aspect of any operating system, providing a way to influence the behavior of software on the system.

In Python, working with environment variables is straightforward and can be crucial for managing configurations, credentials, and other dynamic data.

This tutorial will cover everything you need to know about accessing environment variables in Python, including setting, getting, printing, and reading them.

Table of Contents

  1. Introduction to Environment Variables
  2. Accessing Environment Variables
  3. Practical Examples
  4. Advanced Use Cases
  5. Error Handling
  6. Conclusion

1. Introduction to Environment Variables

Environment variables are key-value pairs that can affect the way running processes will behave on a computer.

They are used to store configuration settings, system information, and other important data that processes might need to function correctly.

Common Use Cases:

  • Configuration Settings: Storing configuration options and parameters.
  • Secrets Management: Storing sensitive information such as API keys and passwords.
  • Environment-Specific Settings: Defining variables that differ between development, testing, and production environments.

Think of environment variables as the secret ingredients in your grandma’s famous recipe. You don’t need to know what they are to enjoy the final dish, but they play a critical role in making everything come together perfectly.

2. Accessing Environment Variables

Python provides a convenient way to work with environment variables through the os module.

This module allows you to interact with the operating system in a portable way, making your code more adaptable and easier to maintain.

Get Environment Variables

To read or get an environment variable in Python, you can use the os.getenv method or access the os.environ dictionary.

Example:

import os

# Using os.getenv
db_host = os.getenv('DB_HOST')
print(f"Database Host: {db_host}")

# Using os.environ
db_user = os.environ.get('DB_USER')
print(f"Database User: {db_user}")
Enter fullscreen mode Exit fullscreen mode

The os.getenv function returns None if the environment variable does not exist, whereas os.environ.get can also take a default value to return if the variable is not found.

Example with Default Value:

import os

db_host = os.getenv('DB_HOST', 'localhost')
print(f"Database Host: {db_host}")
Enter fullscreen mode Exit fullscreen mode

Here, if DB_HOST isn't set, it defaults to 'localhost', ensuring your application has a sensible fallback.

Set Environment Variables

To set an environment variable, you use the os.environ dictionary.

Example:

import os

# Setting an environment variable
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_USER'] = 'admin'

print(f"Database Host: {os.environ['DB_HOST']}")
print(f"Database User: {os.environ['DB_USER']}")
Enter fullscreen mode Exit fullscreen mode

By setting environment variables, you can dynamically adjust your application's behavior without changing the code.

This can be incredibly useful in development and production environments where settings often differ.

Delete Environment Variables

You can delete an environment variable using the del keyword on the os.environ dictionary.

Example:

import os

# Deleting an environment variable
del os.environ['DB_USER']

# This will now raise a KeyError
try:
    print(os.environ['DB_USER'])
except KeyError:
    print("DB_USER variable does not exist")
Enter fullscreen mode Exit fullscreen mode

Deleting environment variables can help you clean up settings that are no longer needed or to ensure that sensitive information is removed after use.

3. Practical Examples

Let’s dive into some practical examples to see how environment variables can be used effectively in real-world scenarios.

Example 1: Managing Database Configuration

Using environment variables to manage database configuration can help you avoid hardcoding sensitive information in your scripts.

This is like keeping your recipe secret safe and not written down for anyone to find.

import os

# Get database configuration from environment variables
db_config = {
    'host': os.getenv('DB_HOST', 'localhost'),
    'user': os.getenv('DB_USER', 'root'),
    'password': os.getenv('DB_PASSWORD', ''),
    'database': os.getenv('DB_NAME', 'test_db')
}

print(db_config)
Enter fullscreen mode Exit fullscreen mode

By pulling these settings from environment variables, you can easily switch databases or change credentials without modifying your code. Just update the environment variables, and you’re good to go!

Example 2: Reading API Keys

Storing API keys in environment variables is a common practice to keep your keys secure and out of your source code.

import os

# Reading an API key from an environment variable
api_key = os.getenv('API_KEY')

if api_key:
    print("API Key found")
else:
    print("API Key not found. Please set the API_KEY environment variable.")
Enter fullscreen mode Exit fullscreen mode

This ensures that your API keys remain confidential, reducing the risk of them being exposed in version control systems or shared inappropriately.

4. Advanced Use Cases

Now that we've covered the basics, let’s explore some advanced use cases where environment variables can be particularly powerful.

Managing Secrets

When managing secrets such as passwords or tokens, environment variables can be a safer alternative than hardcoding them into your codebase.

import os

# Example of managing secrets
aws_access_key = os.getenv('AWS_ACCESS_KEY')
aws_secret_key = os.getenv('AWS_SECRET_KEY')

if aws_access_key and aws_secret_key:
    print("AWS credentials found")
else:
    print("AWS credentials not found. Please set the AWS_ACCESS_KEY and AWS_SECRET_KEY environment variables.")
Enter fullscreen mode Exit fullscreen mode

By storing secrets in environment variables, you can keep them secure and manage access more effectively.

Configuring Applications

Environment variables can be used to configure applications dynamically, allowing different settings based on the environment (development, testing, production).

This is like adjusting the recipe slightly for different occasions.

import os

# Example configuration based on environment
env = os.getenv('ENV', 'development')

if env == 'production':
    debug = False
    db_host = os.getenv('PROD_DB_HOST')
else:
    debug = True
    db_host = os.getenv('DEV_DB_HOST', 'localhost')

print(f"Debug mode: {debug}")
print(f"Database Host: {db_host}")
Enter fullscreen mode Exit fullscreen mode

This approach ensures that your application behaves correctly in different environments, improving both security and performance.

Environment-Specific Settings

Using environment variables for environment-specific settings helps in creating a consistent deployment strategy across different environments.

Think of it as customizing the recipe for different tastes.

import os

# Example of environment-specific settings
env = os.getenv('APP_ENV', 'development')

config = {
    'development': {
        'db_host': os.getenv('DEV_DB_HOST', 'localhost'),
        'debug': True
    },
    'production': {
        'db_host': os.getenv('PROD_DB_HOST'),
        'debug': False
    }
}

current_config = config[env]

print(f"Current configuration: {current_config}")
Enter fullscreen mode Exit fullscreen mode

This makes it easier to manage different configurations without altering the code, simply by setting the appropriate environment variables.

5. Error Handling

When working with environment variables, it's important to handle cases where variables might not be set.

This ensures that your application can fail gracefully or provide meaningful error messages.

Example:

import os

# Handling missing environment variables
try:
    db_host = os.environ['DB_HOST']
except KeyError:
    db_host = 'localhost'
    print("DB_HOST environment variable not set. Using default 'localhost'.")

print(f"Database Host: {db_host}")
Enter fullscreen mode Exit fullscreen mode

You can also use os.getenv with a default value to avoid KeyErrors, providing a fallback in case the environment variable is not set.

import os

# Using os.getenv with a default value
db_host = os.getenv('DB_HOST', 'localhost')
print(f"Database Host: {db_host}")
Enter fullscreen mode Exit fullscreen mode

By incorporating error handling, you can make your application more robust and user-friendly.

6. Conclusion

Environment variables are a powerful and flexible way to manage configurations and sensitive information in your Python applications.

By understanding how to set, get, print, and read environment variables, you can make your applications more secure and easier to configure across different environments.

Summary:

  • Getting Environment Variables: Use os.getenv or os.environ.get.
  • Setting Environment Variables: Use os.environ.
  • Deleting Environment Variables: Use del on os.environ.

By mastering the use of environment variables, you can enhance the security, flexibility, and maintainability of your Python applications.

Experiment with these techniques in your projects to see how they can simplify your configuration management.

Happy coding!

Top comments (0)