Managing Environment Variables in Python with python-dotenv

Posted by Afsal on 29-Sep-2023

Hi Pythonistas!

Today we will learn how to manage environment variables in Python. We know that while working on projects that run on multiple environments some of the variables change according to the environment like database details, API key etc. If we hard code these variables in our code is a terrible idea because whenever we deploy a different environment or if there are multiple developers these values change every time. For that we can use a file called .env and place all the environment variables there. In our code we are using a package called python-dotenv. Let us dive into the code

Installation

pip install python-dotenv

create a .env file

VAR1=hello

VAR2=world

I have create .env with about variables

Code

from dotenv import load_dotenv
import os

load_dotenv()

VAR1 = os.environ.get("VAR1")
VAR2 = os.environ.get("VAR2")

print(f'{VAR1} {VAR2}')

Output

hello world

load_dotenv function load the environment variable

We are accessing the variable using the os module

By using this we can make our code portable also more secure because we don't have to hard code the sensitive details like password, API key etc in code

Hope you have learned something from this post please share your valuable suggestions with afsal@parseltongue.co.in