How to use dotenv package to load environment variables in Python

Pratik Choudhari

Working with environment variables in Python is easy, getting and setting of variables is done using the os standard library, however, what if a user wants to set the environment variables when a program is executed and also avoid version controlling the variable values? The dotenv package does exactly that.

In this article, we will see how dotenv can be used to load and use environment variables from a file.

Installation

pip3 install python-dotenv

Storing the values in .env file

dotenv loads the environment variable by reading them from a .env file which needs to be inside the project directory.

The .env file has declarations in the form of key-value pairs separated by =, following is an example of the contents of a .env file.

ACCESS_TOKEN=ABC123 SECRET_TOKEN=SUPERSECRET123

Using Multi-line values:

ACCESS_TOKEN=ABC123 SECRET_TOKEN="SUPERSECRET123 CONTINUEDSECRET"

OR

ACCESS_TOKEN=ABC123 SECRET_TOKEN="SUPERSECRET12\nCONTINUEDSECRET"

A variable's value can be used again in the same file using the ${VAR} syntax.

ROOT_PATH=home/user LOGS_PATH=${ROOT_PATH}/logs

Loading .env file

Loading as environment variable

The dotenv package provides a load_dotenv() method which reads the file provided as a file path. If no path is specified, ./.env is used as the default path which means it looks for .env file in the Python script directory.

from dotenv import load_dotenv load_dotenv()

Loading as a dictionary

Using this method, environment variables are not affected. Instead, they are parsed and converted into a Python dictionary.

from dotenv import dotenv_values config = dotenv_values(".env") print(config)

Output:

{'ACCESS_TOKEN': 'ABC123', 'SECRET_TOKEN': 'SUPERSECRET12'}

Versioning environment variables

A project can have multiple instances like testing, development, staging or production. When using different instances different environment variables can be needed. Therefore, to solve this issue, a project can use multiple .env files like

Segregation of variables into different files can allow us to version control environment files.

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses