Settings and Secrets in a .env File
Most programs need a few settings that are not part of their instructions: the address of a service to talk to, a choice such as metric or imperial units, and sometimes a secret key that proves who is calling. These values change from one computer to another, and the secret ones must never be shown to anyone else. Keeping settings outside the code lets the same program run anywhere, and lets the code be shared without giving a secret away.
Settings that arrive from outside
When a program starts, the system hands it a small collection of named text values. Each one is an environment variable: a name, such as UNITS, paired with a value, such as metric. The program did not create them and does not have to read any file to get them. They come from whatever started it, usually the terminal, which passes its own environment on to every program it launches.
That makes environment variables a natural place for settings. The code asks for a setting by name, and the value can differ on every computer without a single line of code changing.
- terminal
- the environment
- the running program
Python gives a program its environment through the standard library module os. Its os.environ works like a dictionary: the keys are the names and the values are the settings. There are two ways to read one, and they behave differently when the name is missing.
import os
units = os.getenv("UNITS", "metric")
key = os.getenv("WEATHER_API_KEY")
print(units) # metric, when UNITS is not set
print(key) # None, when WEATHER_API_KEY is not set
city = os.environ["CITY"] # KeyError: 'CITY', when CITY is not setos.getenv(name) gives back the value, or None when there is no such name. A second argument is a default used in that case. Square brackets, os.environ[name], look the name up the way a dictionary does, so a missing name raises a KeyError and the program stops unless something handles it.
Every value in the environment is a string. A setting written as TIMEOUT=30 arrives as the text "30", and the program turns it into a number itself with int(os.getenv("TIMEOUT", "10")).
True or false?
Reading a missing name with os.environ["CITY"] gives None.
False. Square brackets raise a KeyError for a missing name, as with a dictionary. It is os.getenv("CITY") that gives None.
A setting TIMEOUT=30 arrives in the program as the string "30".
True. Every environment variable is text. The program converts it with int() when it needs a number.
A .env file fills the environment
Setting every variable by hand in the terminal before each run is tiresome, and the commands differ between systems. The usual answer is a .env file (said "dot env"): a plain text file, saved in the project folder, that lists the settings one per line as NAME=value. A line starting with # is a comment.
# Settings for the weather program
WEATHER_URL=https://api.example.com/weather
WEATHER_API_KEY=wk_51f0c9d2e7a4
UNITS=metricPython does not read this file by itself. The third-party package python-dotenv does: it is added to a project under that name and imported under the name dotenv. Its function load_dotenv() finds the file, reads each line and adds every name and value to os.environ. From then on the program reads the settings exactly as before, with os.getenv, as if they had come from the terminal.
import os
from dotenv import load_dotenv
load_dotenv()
print(os.getenv("UNITS")) # metric- .env file NAME=value lines
- load_dotenv()What load_dotenv() does
It looks for
.envin the folder of the Python file that called it, then in each folder above, and adds every setting it finds toos.environ. - os.environ names and values
- os.getenv() reads UNITS, gives "metric"
- .env file to load_dotenv()
- load_dotenv() to os.environ
- os.environ to os.getenv()
Three details of load_dotenv() explain most surprises:
- It looks for
.envin the folder of the Python file that calls it, then in each folder above that one, not in the folder the terminal happens to be in. - A missing file is not an error. It loads nothing, gives back
Falseand the program carries on, so a missing setting only shows up later, when the program reads it. - It does not replace a variable that is already set. If
UNITSalready came from the terminal, that value stays and the line in the file is skipped.
Many projects also keep a second file, often called .env.example. This is a common habit, not a rule of any tool. It lists every setting the program expects, with harmless placeholder values in place of the secret ones, so a person setting the program up on a new computer copies it to .env and fills in their own values.
WEATHER_URL=https://api.example.com/weather
WEATHER_API_KEY=put-your-key-here
UNITS=metricTrue or false?
When there is no .env file, load_dotenv() stops the program with an error.
False. It loads nothing and returns False. The program carries on, and a missing setting only appears when it is read.
If UNITS is already set when the program starts, load_dotenv() keeps that value and skips the line in .env.
True. By default it never replaces a variable that is already there. The file only fills in what is missing.
Why a secret never goes into the code
Many online services hand out an API key: a long string a program sends with each request to prove who is calling. Whoever holds the key can use the service in your name, and the service bills or blocks your account for what they do. An API key is therefore a secret, treated like a password.
Code, on the other hand, is made to be shared. It is shown to classmates and pasted into questions. Above all, it is kept in version control: a tool, usually Git, that saves a snapshot of the project's files each time you ask it to. Each saved snapshot is called a commit, and all the commits together form the project's history.
That history is often copied to a shared place such as GitHub, where others can make their own copies of it. A key typed into a Python file travels with every one of those copies.
History is the part that catches people out. Deleting the key from the file in a new commit does not remove it from the earlier commit, which still holds it, and copies of the project that others made keep it too. GitHub's own scanner searches the whole history of a repository for keys for exactly this reason. Once a key has been committed and shared, the only safe fix is to cancel it with the service and create a new one.
With settings in a .env file, the code holds only the name WEATHER_API_KEY, and the secret value stays in one file on your own computer. What remains is to make sure that one file is never saved into the history. Git reads an ignore list for this: a file named .gitignore in the project folder, one pattern per line, naming the files Git should leave out.
# Settings with secrets stay on this computer
.envThe line .env tells Git to leave out any file with that name. Add it before the first commit, and here is why. Once a file has been in a commit, Git is tracking it: it keeps saving that file's changes. The ignore list only affects files Git is not yet tracking. So a .env that was already committed stays tracked, and every new commit saves it again, until it is removed from tracking. Even then the earlier commits still hold it, so its key still has to be replaced.
The example file is different. It holds placeholders only, so it is meant to be shared and stays in the history.
| File | Holds | In the shared history |
|---|---|---|
| app.py | the code, which reads settings by name | yes |
| .env.example | every setting name, with placeholders | yes |
| .gitignore | the list of files Git leaves out | yes |
| .env | the real values, including the key | never |
True or false?
Adding .env to .gitignore after it was committed removes it from the history.
False. The ignore list only affects files Git is not tracking yet. The committed copy stays, and the key in it has to be replaced.
A .env.example file with placeholder values is safe to commit and share.
True. It shows which settings exist without any real secret, which is its whole purpose.
One module that reads every setting
A program split into several modules could call os.getenv wherever it needs a setting. Then the names are scattered across files, each place handles a missing value its own way, and a missing key shows up only when the code that uses it finally runs, perhaps halfway through the program, as a confusing failure.
The tidier design gives settings a module of their own, often called config.py. It loads the .env file, reads every setting once, checks the ones the program cannot do without, and stores each in a name written in capital letters, a common way to mark a value that is set once and never changed afterwards.
import os
import sys
from dotenv import load_dotenv
load_dotenv()
def require(name: str) -> str:
value = os.getenv(name)
if not value:
sys.exit(f"Missing setting {name}: add it to the .env file (see .env.example).")
return value
WEATHER_URL = require("WEATHER_URL")
WEATHER_API_KEY = require("WEATHER_API_KEY")
UNITS = os.getenv("UNITS", "metric")The function require reads one setting and checks it. The test if not value is true for None, when the name is missing, and also for the empty string, which is what a line such as WEATHER_API_KEY= with nothing after the equals sign produces.
When the check fails, sys.exit from the standard library module sys ends the program at once. Given a string, it prints that string as the error message and ends the program with a status that signals failure. Here the message names the setting and says where to put it, so the person running the program knows exactly what to do. A setting with a sensible default, such as UNITS, simply uses os.getenv with that default.
Every other module imports the values it needs by name, for example from config import WEATHER_URL, WEATHER_API_KEY. Importing runs config.py once, from top to bottom, so all the checks happen as soon as the program starts, before any real work begins.
- .env real values
- config.py loads, reads, checks
- main.py
- weather.py
- .env to config.py: load_dotenv()
- config.py to main.py: from config import
- config.py to weather.py: from config import
$ uv run main.py
Missing setting WEATHER_API_KEY: add it to the .env file (see .env.example).Because every setting is read in one place, the list of settings the program needs is in one file, a missing one is reported the same clear way every time, and changing a setting's name means editing a single line.
True or false?
A check written as if value is None also catches the line WEATHER_API_KEY= with nothing after the equals sign.
False. That line gives the empty string, not None. if not value catches both.
When the other modules import from config.py at their top, a missing setting is reported as soon as the program starts.
True. Importing runs config.py at once, so its checks run before any other step of the program.