Using .env files within Python

I have been trying a lot of Node.js tutorials, putting my hands to learning a new skill and all that, especially during COVID-19. Using enviroment variables has always been easy in node especially with packages such as dotenv which allows getting your variables from your .env file with ease.

// .env
// nodeFile.js

const db = host: process.env.DB_HOST,

But when using enviroment variables within Python, I have always found that a little tricky, mainly because if you're in an virtual enviroment and you set variables in that enviroment. Once you stop it, they're forgotten.

This is of course unless you keep them in your .zsh file. But then if you upload your dotfiles to Github they're stored in the repo.

Enter python-dotenv a sweet package from Saurabh Kumar that allows you to use .env within your Python projects. Whilst I am working through node tutorials, I still like to brush up on my Python. Having a package like this has made my life a tone easier when it comes to managing keys.

Let me walk you through how to get set up

Install the latest version

pip install -U python-dotenv

Assuming you have created the .env file along-side your settings module.

├── .env

Add the following code to your

from dotenv import load_dotenv

# OR, the same with increased verbosity

# OR, explicitly providing path to '.env'
from pathlib import Path  # python3 only
env_path = Path('.') / '.env'

At this point, parsed key/value from the .env file is now present as system environment variable and they can be conveniently accessed via os.getenv():

import os
SECRET_KEY = os.getenv("EMAIL")

You can find more information about python-dotenv via the repo. I think this is a great package, and i'll be using it in all my Python development.

2022 No rights reserved.
3D Heart