You are currently viewing Using python-dotenv Load Environment Variables?

The python-dotenv package is popular for managing environment variables and keeping sensitive information out of code repositories. In this article, we will discuss how to use python-dotenv to load environment variables from a .env file in your Python projects.

Advertisements

We will also cover the installation process, how to store environment variables in a .env file, how to load the .env file, and best practices for version controlling your .env file. Before anything else, let’s see how we can use it briefly.

1. python-dotenv to Load Environment Variables

We will discuss each step in detail letter on, If you hurry this section is for you. It is a quick guide that will give you an idea of how to use python-dotenv to load environment variables.

  • Create a new virtual environment.
  • Activate the virtual environment.
  • Install the python-dotenv package.
  • Create a new file called .env in the root directory.
  • Add your environment variables as key-value pairs.
  • Import the load_dotenv function.
  • Call the load_dotenv function to load the environment.
  • Use the os.getenv function to get the value of a specific environment variable.

See the following example, where we use the python-dotenv package to access the environment variables from .env file.


# Using python-dotenv to Load Env variables
from dotenv import load_dotenv
import os

load_dotenv()

my_password = os.getenv("Password")
print(f"Password:{my_password}")

# Output:
# Password:IamPassword123

Here is each step in more detail:

2. Create Virtual Environment

Before we begin using the python-dotenv package, let’s set up a virtual environment for our project. A virtual environment allows us to create an isolated Python environment, separate from the global Python installation.

To create a new virtual environment, follow these steps:

  • Open your terminal and navigate to your project’s root directory.
  • Run this command on your terminal, python -m venv venv
  • Now activate the virtual environment, venv/Scripts/activate

Congrats, you have now created your virtual environment and activated it. Now the next step is to install the python-dotenv package.

3. Install python-dotenv Package

python-dotenv is a third-party package that needs to be installed before you can use it in your Python projects. You can now install the python-dotenv package using pip. To install python-dotenv, enter the following command:


# Install python-dotenv
pip install python-dotenv

4. Store The variables in .env File

Before you can use python-dotenv to load environment variables into your Python project, you need to store your variables in a .env file. This file should be located in your project’s root directory and should contain all the variables you need to use in your project, each as a key-value pair separated by an equals sign.

Below is a Sample .env file:


# .Env file
DB_HOST=localhost
DB_PORT=5432
DB_NAME=mydatabase
DB_USER=myusername
DB_PASSWORD=mypassword

5. Load .env File

Now that you have created a .env file containing your environment variables, you can use python-dotenv to load these variables into your Python project.

To load the variables from your .env file, you first need to import the load_dotenv function from the dotenv module.


# Load .env file

# Import load_dotenv
from dotenv import load_dotenv

load_dotenv()

Make sure that the load_dotenv function is called before accessing any of the environment variables in your code.

6. Access the Environment Variables

To access an environment variable, you first need to import the os module, which provides a way to interact with the operating system and read the environment variables.

See the example for the .env file we created earlier:


# Access environment variables
import os

# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()

# Access environment variables
DB_HOST = os.getenv("DB_HOST")
DB_PORT = os.getenv("DB_PORT")
DB_NAME = os.getenv("DB_NAME")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")

# You can now use it
print("Db_HOST")

7. Different Versions of Environment Variables

A project can use multiple .env files for different users or different environments in the process of development. The python-dotenv solve this issue as well. You can store different environment variables in differnt files. Segregating variables into different files allows for version control of environment files, making it easier to manage configuration values across different environments.

You can specify which .env file to load by passing the appropriate dotenv_path argument to the load_dotenv() function.

Let’s say you are working with API you might create the following different files for the different version of keys:

For Testing:


# .Env.testing
API_KEY=1234testing

For Production:


# .Env.production
API_KEY=9012production

You can now Specify the environment for each of the Environment variables in just one line:


import os
from dotenv import load_dotenv
# This one is for the Development Env
env = os.getenv('ENVIRONMENT', 'development')
dotenv_path = f'.env.{env}'
load_dotenv(dotenv_path=dotenv_path)

api_key = os.getenv('API_KEY')
# Use the API key in your code

Frequently Asked Questions

What is python-dotenv?

python-dotenv is a Python library that helps load environment variables from a file named .env into os.environ when the Python script is run. This is useful for managing configuration settings, API keys, and other sensitive information in your applications.

What is the purpose of the .env file?

The .env file is a text file where you store your environment variables. Each variable is defined as a key-value pair, e.g., API_KEY=your_api_key.

Where should I place the .env file?

The .env file is typically placed in the root directory of your project, alongside your main Python script or application.

Is it safe to store sensitive information in the .env file?

The .env file should not be shared or version-controlled as it may contain sensitive information. It’s typically added to the .gitignore file to avoid unintentional exposure.

Do I need to call load_dotenv() in every script?

It’s recommended to call load_dotenv() in each script that needs access to the environment variables, typically at the beginning of the script.

Can I override existing environment variables with python-dotenv?

You can override existing environment variables with python-dotenv. By default, if a variable already exists in the environment, load_dotenv() will not overwrite it. However, you can override this behavior by using the override parameter.

Summary and Conclusion

We have discussed how to use python-dotenv package to load environment variables in Python. Managing configuration values with environment variables are good for building secure Python applications. We have also learned how to version your environment variables for different environments using multiple .env files. Leave queries in the comment section.

Happy Coding!