Environment Variables in Python

Environment variables are essential elements in Python programming that store key-value pairs at the system level. They play a crucial role in enhancing the security and flexibility of applications.

In this blog post, we will explore the benefits of using environment variables in Python and provide a comprehensive guide on how to effectively leverage their power.

Benefits of Using Environment Variables

Environment variables offer several advantages when developing Python applications. By utilizing environment variables, you can:

  1. Improve Security: Environment variables allow you to store sensitive information, such as API keys and database credentials, separately from your code. This ensures that sensitive data remains hidden from unauthorized access.
  2. Enhance Flexibility: By utilizing environment variables, you can easily adapt your application to different environments without modifying the code. This enables seamless deployment across various systems and simplifies configuration management.

Read: How to create a Modern Python Development Environment

Setting up Environment Variables in Python

To set environment variables in Python, the os module comes to the rescue. Here’s how you can use it:

# set environment variables Python

os.environ[‘USERNAME’] = ‘username’

os.environ[‘PASSWORD’] = ‘password’

By assigning values to the os.environ dictionary, you can set environment variables within your Python code. In this case, we’re setting USER and PASSWORD variables.

Getting Environment Variables

Retrieving environment variables is just as simple as setting them. The os module provides methods to access these values. Here’s an example:

# Python get environment variables

USERNAME = os.getenv(‘USERNAME’)

PASSWORD = os.getenv(‘PASSWORD’)

By using os.getenv(), you can retrieve the values of environment variables. In this example, we assign the values of USERNAME and PASSWORD to the variables USERNAME and PASSWORD, respectively.

Read: Windows 10 environment variables

Handling Non-Existent Keys

When attempting to retrieve non-existent environment variables, it’s essential to handle the potential errors gracefully. The methods os.getenv() and os.environ.get() both return None if the requested key does not exist. However, accessing a non-existent key directly from the os.environ dictionary raises a KeyError. Here’s an example:

# Retrieving non-existent keys

VAR1 = os.getenv(‘VAR1’)

VAR2 = os.environ.get(‘VAR2’)

VAR3 = os.environ[‘VAR3’] # KeyError: key does not exist.

VAR1 and VAR2 will be assigned None since they don’t exist as environment variables. However, attempting to access VAR3 directly from the os.environ dictionary will raise a KeyError.

Read: How to install Python on Ubuntu 22.04 

The Benefits of Environment Variables

Environment variables offer numerous advantages in application development. Here are a few use cases where environment variables prove invaluable:

Securing Sensitive Information: Environment variables provide a secure way to store sensitive data such as API credentials. Instead of hard-coding these credentials into your code, you can fetch them from environment variables at runtime. This practice helps protect your credentials and prevents accidental exposure in your code repository.

Environment-Specific Configurations: Environment variables allow you to customize your application’s behavior based on the environment it runs in. Whether you’re developing, testing, or deploying in different environments, you can utilize environment variables to adjust settings accordingly. This flexibility ensures your code adapts seamlessly to various deployment scenarios.

Read: How is the path environment variable managed in Linux/Ubuntu/Debian

Storing Local Environment Variables

When developing Python code, it’s essential to accommodate accessing environment variables from different environments. The Python Decouple package simplifies this process. Here’s how you can use it:

Install Python Decouple in your local Python environment:

$ pip install python-decouple

Create a .env file in your project’s root directory to store your environment variables:

$ touch .env #creation of a new .env file

$ nano .env #opening the .env file using nano editor

Add your environment variables to the .env file using the following format:



Save the file and exit the text editor. Your environment variables are now securely stored in the .env file. To prevent accidentally committing this file to your code repository, remember to add it to your .gitignore file.

Now, you can access these environment variables in your Python code using Python Decouple:

from decouple import config. # Python decouple module


KEY = config(‘KEY’)

By importing the config function from the decouple module, you can retrieve the values of the environment variables defined in your .env file. In this example, USERNAME and KEY will be assigned the values of USERNAME and KEY, respectively.

Read: How to run Python on Android

Advantages of Using Python Decouple

Utilizing Python Decouple to handle environment variables offers several advantages. Here are a few key benefits:

Seamless Cloud Deployment: When deploying your application to a cloud service, Python Decouple ensures that your code can access environment variables regardless of the deployment method or interface provided by the cloud service. This compatibility allows for smooth integration with various cloud platforms.

Standardized Variable Naming: Following common conventions, Python Decouple encourages the use of capital letters for naming global constants in your code. This standardization enhances code readability and maintainability.


If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.


Marianne elanotta

Marianne is a graduate in communication technologies and enjoys sharing the latest technological advances across various fields. Her programming skills include Java OO and Javascript, and she prefers working on open-source operating systems. In her free time, she enjoys playing chess and computer games with her two children.

Leave a Reply