Python libraries for loading .env

Leomahendradev


Picture this. You build a Django project, and inside settings.py you write your secret key and your database password. It runs fine. Then you push the project to GitHub, and now anyone on the internet can read your password.

This happens to developers all the time, and it is hard to undo. Once a secret is in Git history, it stays there, even if you delete the line later.

The fix is simple. Keep secrets out of your code and put them in a separate file called .env. You add that file to .gitignore, so it never leaves your computer. Your code only reads the values when it runs.

Python has several ways to read a .env file. Let us look at the main ones, and I will tell you which one I use.

What does a .env file look like?

It is a plain text file with one NAME=value pair on each line:

SECRET_KEY=my-very-secret-value
DEBUG=False
DATABASE_PASSWORD=another-secret

The same code can now run on your laptop, on a test server and on a live server. Only the .env file is different on each one. That is the second big reason people use it: settings change from place to place, and code should not.

A trap that explains why these libraries exist

Everything you read from a .env file is text. Even False is just the word "False", not the real Python False. See what happens:

import os

DEBUG = os.getenv("DEBUG")
print(DEBUG)        # 'False'
print(bool(DEBUG))  # True

In Python, any non-empty text counts as True. So your app thinks DEBUG is on, while your file says it is off. On a live website, that can show private error details to your visitors.

Some libraries solve this by converting the text into the right type for you. Keep this in mind as we go.

1. python-dotenv

This is the most popular one, and the simplest. It reads the .env file and puts the values into the environment, so you can read them with os.getenv.

pip install python-dotenv
import os

from dotenv import load_dotenv

load_dotenv()  # reads the .env file

SECRET_KEY = os.getenv("SECRET_KEY")

It finds the file on its own, and it works with Django, Flask and FastAPI. The only downside is that you still get text back, so you must convert types yourself.

2. environs

It does the same job, and also converts types and checks the values for you.

pip install environs
from environs import Env

env = Env()
env.read_env()  # reads the .env file

SECRET_KEY = env.str("SECRET_KEY")
DEBUG = env.bool("DEBUG", default=False)

env.bool turns the text "False" into a real False. It can also make numbers and lists. It is a good choice for big projects with many settings.

3. python-decouple

This is the one I use. It has been my default choice for more than a year, and I never had a reason to change.

pip install python-decouple
from decouple import config

SECRET_KEY = config("SECRET_KEY")
DEBUG = config("DEBUG", cast=bool, default=False)

Why I like it: it is small, the code is easy to read, and cast=bool fixes the trap we saw above in the same line. It reads both .env and .ini files.

There is one more feature that really helps me. You can tell it to load the .env file from any path you like. This is great when one environment file is shared by more than one app:

from decouple import Config, RepositoryEnv

config = Config(RepositoryEnv("/path/to/shared/.env"))

SECRET_KEY = config("SECRET_KEY")

4. os.environ

You do not need to install anything, because it is part of Python.

import os

SECRET_KEY = os.environ.get("SECRET_KEY")

It is a great fit for Docker and cloud platforms. There, the host sets the variables for you, so no file is needed. But it cannot read a .env file by itself, so on your laptop you must load the file in some other way. And it gives you text only, so the DEBUG trap is still there.

5. django-environ

This one is made only for Django.

pip install django-environ
import environ

env = environ.Env()
environ.Env.read_env()  # reads the .env file

SECRET_KEY = env("SECRET_KEY")
DEBUG = env.bool("DEBUG", default=False)

Its best feature is turning a web address into a Django settings block. For example, env.db() reads a DATABASE_URL and builds the whole DATABASES setting for you. env.cache() does the same for a cache address. That makes PostgreSQL and Redis setups much shorter.

Comparison

Library Best for Converts types Ease of use
python-dotenv General use No Easy
environs Bigger projects with many settings Yes Easy
python-decouple A small, clean setup Yes Very easy
os.environ Docker and cloud platforms No Manual
django-environ Django projects Yes Easy, Django only

Which one should you choose?

If you want the simplest thing that works, take python-dotenv or python-decouple. If your project has lots of settings and you want checks, take environs. If you only build Django apps and like the database shortcut, take django-environ.

My own pick is python-decouple. The code stays short, the types are handled in one line, and I can load the environment file from another folder when several apps share it.

One last reminder: whichever library you pick, add .env to your .gitignore before your first commit.