Calmcode - env variables: dotenv

Using dotenv files

1 2 3 4 5 6

Instead of passing environment variables manually beforehand in a session, you can also define them in a .env file. This is a file that contains key-value pairs that are loaded into the environment when you start your program.

# .env
FOOBAR=10000
HELLO="WORLD"

To access these variables we will first need to install a Python package.

uv pip install python-dotenv

Note that you must install python-dotenv but that you will load from the dotenv module in Python. This is slightly confusing but be aware that the name of the package from pip is different than from Python itself.

Here's how you might load the variables from Python.

import os
from dotenv import load_dotenv

load_dotenv(override=True)
print(os.environ["FOOBAR"])
print(os.environ["HELLO"])

The override=True argument is optional but it will make sure that the variables in the .env file will overwrite any existing variables in the environment. This is useful if you want to make sure that the variables are always the same.