Environment variables in Python: os.environ, .env files and secrets out of your code
Your API key works on your laptop and vanishes on the server, or worse, ends up on GitHub. Learn to read configuration with os.environ, load a .env file and keep secrets safe.
You write your first script that calls an API. To test quickly, you paste the key into the code: API_KEY = "sk-...". It works. You commit, push the repository and, a few hours later, someone else is using your key. A secret written in the code travels with the code.
Environment variables solve that problem. They are NAME=value pairs the operating system hands to each program when it starts. Your code reads the value at runtime, and the same .py file can use a local database on your laptop and another one in production without changing a line. The short definition lives in the glossary.
Read a variable with os.environ
Python exposes the process environment as os.environ, which behaves like a dictionary. This example sets two variables inside the program so you can run it as is, for example in Python online; in a real project you would set them outside the code:
import os
os.environ["APP_MODE"] = "development"
os.environ["DEBUG"] = "false"
mode = os.environ.get("APP_MODE", "production")
port = int(os.environ.get("PORT", "8000"))
debug = os.environ.get("DEBUG", "false").lower() in {"1", "true", "yes"}
print(mode, port, debug)development 8000 FalseThree details in those lines:
os.environ.get("PORT", "8000")returns the default when the variable doesn't exist.PORTisn't set, so we get8000.- Everything arrives as a string. The port is converted with
int(). Without it,port + 1fails with aTypeError. "false"is a non-empty string, and in Python any non-empty string is truthy. That's whydebugis compared explicitly with the values we accept as "yes".
When the variable is required
A default makes sense for the port, but not for an API key: if it's missing, the program should stop at startup with a clear message rather than fail later with a confusing error. os.environ["API_KEY"] would raise a KeyError; a small function gives a better message:
import os
def required(name):
value = os.environ.get(name)
if not value:
raise RuntimeError(f"Missing environment variable {name}")
return value
os.environ.pop("API_KEY", None) # pretend it is not set
try:
required("API_KEY")
except RuntimeError as error:
print(error)Missing environment variable API_KEYif not value also rejects a variable that is set but empty (API_KEY=), which in practice is usually a configuration mistake.
Set them in the terminal
A program receives the environment variables of the terminal you start it from. On Linux and macOS:
export API_KEY="your-key"
python app.pyIn Windows PowerShell you write $env:API_KEY = "your-key" before python app.py. Either way the value lasts as long as that terminal session. If you change os.environ from Python, the change only affects that process and the processes it starts; it doesn't touch your terminal or your system.
A .env file for development
Typing export every time you open a terminal gets old. In development it's common to keep the values in a .env file at the project root:
# .env (never committed)
API_KEY=your-development-key
DATABASE_URL=sqlite:///local.db
DEBUG=trueThe python-dotenv package (install it with pip install python-dotenv) reads it and copies its values into os.environ at startup:
import os
from dotenv import load_dotenv
load_dotenv() # finds a .env file and loads its variables
database_url = os.environ.get("DATABASE_URL", "sqlite:///local.db")By default, load_dotenv() does not overwrite a variable that already exists in the environment. That's what you want: in production the server sets the real values and the local .env stays out of the way.
Keep the .env off GitHub
Add .env to your .gitignore before the first commit. To tell others which variables the project needs, commit a .env.example instead, with the names and fake values (API_KEY=replace-me).
If a secret already reached the repository, deleting it in a new commit isn't enough: it stays in the git history. Revoke the key and issue a new one; that's the only thing that makes it useless to whoever copied it.
Two more common slips: printing the whole configuration to the logs while debugging (the secrets end up in a logging service) and putting keys in a notebook you later share.
A quick check
Before moving on, answer without running it: if RETRIES is "3", what does print(os.environ.get("RETRIES") * 2) print? It prints 33, because it repeats a string. If you expected 6, go back to the section on types.
Environment variables pair well with virtual environments: the virtual environment isolates each project's packages and environment variables isolate its configuration. Keep the Python cheat sheet nearby for the rest of the syntax, and see the os.environ documentation.