Chapter 1 · Your Developer Toolbox
Environment Variables, .env Files and Virtual Environments
- Page 3 of 22
- 15 min read
An AI application needs settings that must not be written into its code: the API key for an LLM provider, the model name, a database URL, a debug switch. It also needs the right versions of its packages — the FastAPI and requests your code was tested with, not whatever happens to be installed on the laptop next to you. This page covers both: environment variables and .env files for settings and secrets, and virtual environments for packages, first with the standard venv + pip, then with uv, the faster tool most new Python projects use in 2026.
Get this right once and you avoid two of the most common beginner disasters: an API key pushed to GitHub, and "it works on my machine".
What you will learn
- What environment variables are, how to set them in the shell (
export,$VAR) and read them in Python (os.environ) - What
PATHis and how the shell finds a program when you type its name - How to keep secrets in a
.envfile and load them with python-dotenv - How to install and check Python and Git, create a virtual environment, and record packages in
requirements.txt - How to do the same with uv (
uv init,uv add,uv run,pyproject.toml,uv.lock), and how to lay out a project folder
Environment variables
Every running program carries a small dictionary of text settings called its environment. The shell has one, and every program you start from it receives a copy. Some are set for you:
echo "$HOME"
echo "$USER"/home/nadia
nadia$NAME is replaced by the variable's value before the command runs. Now make your own. There is a subtle difference between a shell variable (known only to the shell) and an environment variable (passed on to programs); export turns the first into the second:
MODEL_NAME=practice-llm-1
echo "$MODEL_NAME"
python3 -c 'import os; print(os.environ.get("MODEL_NAME"))'
export MODEL_NAME
python3 -c 'import os; print(os.environ.get("MODEL_NAME"))'practice-llm-1
None
practice-llm-1Before export, Python saw None: the variable lived only inside the shell. After it, every program started from this shell sees it. Usually you do both at once with export NAME=value. Two rules of bash syntax: no spaces around =, and quote values that contain spaces (export GREETING="hello there").
You can also set a variable for one command only, by writing it in front:
LOG_LEVEL=debug python3 -c 'import os; print(os.environ["LOG_LEVEL"])'
echo "after: ${LOG_LEVEL:-not set}"debug
after: not set${LOG_LEVEL:-not set} means "the value, or not set if there is none". Variables set with export last until you close the terminal; to keep one permanently, add the export line to ~/.bashrc (bash, Git Bash, WSL) or ~/.zshrc (macOS).
Reading them in Python
In Python the environment is os.environ, which behaves like a dictionary of strings:
import os
print(os.environ["MODEL_NAME"]) # must exist, or KeyError
print(os.getenv("TEMPERATURE", "0.2")) # a default when it is missing
max_tokens = int(os.getenv("MAX_TOKENS", "256")) # values are always text: convert them
print(max_tokens + 1)
print(os.environ["LLM_API_KEY"])practice-llm-1
0.2
257
KeyError: 'LLM_API_KEY'Which style to use is a design decision. For something with a sensible default (temperature, log level) use os.getenv(name, default). For something the app cannot work without (an API key, a database URL) use os.environ[name] — it is better that the app stops at start-up with a clear error than that it starts and fails on the first user request. That is the idea behind the settings classes you will meet in FastAPI later.
PATH: how the shell finds programs
When you type git, the shell does not search your whole disk. It looks through the folders listed in the PATH variable, in order, and runs the first file called git it finds. command -v shows which file that is. Let us write a tiny program of our own and see PATH at work:
mkdir -p ~/bin
cat > ~/bin/hello-ai <<'EOF'
#!/usr/bin/env bash
echo "Hello from a script on your PATH"
EOF
chmod +x ~/bin/hello-ai
command -v git
command -v hello-ai || echo "hello-ai is not on the PATH"/usr/bin/git
hello-ai is not on the PATHThe script exists, and chmod +x made it executable, but ~/bin is not one of the folders the shell searches. Put it at the front of PATH (folders are separated by :):
export PATH="$HOME/bin:$PATH"
echo "$PATH" | tr ':' '\n' | head -n 1
command -v hello-ai
hello-ai/home/nadia/bin
/home/nadia/bin/hello-ai
Hello from a script on your PATHThis is exactly what happens behind the scenes when you install Python, Git or uv: the installer puts its folder on the PATH. "command not found" right after an install almost always means the folder is not on the PATH yet (open a new terminal first — PATH is read when the shell starts). And when the wrong Python runs, command -v python shows you which one won.
Installing and checking Python and Git
| System | Python | Git |
|---|---|---|
| Windows | From python.org. Recent releases offer the Python install manager, which gives you the py command (py install 3.14). With a classic installer, tick "Add python.exe to PATH". | winget install --id Git.Git -e --source winget, or the installer from git-scm.com. It includes Git Bash. |
| macOS | brew install [email protected] (Homebrew), or the python.org installer | xcode-select --install (Apple's Git) or brew install git |
| Ubuntu / WSL | sudo apt install python3 python3-venv python3-pip | sudo apt install git |
This course standardises on Python 3.14; every example also runs on 3.12 and 3.13, so a distribution's Python 3.12+ is fine. Python 3.15 came out in October 2026, but some packages and Docker images take a few weeks to catch up. For Git, anything from 2.51 on has all the commands this course teaches. Check what you have:
python3 --version
git --versionYou will see something like Python 3.14.8 and git version 2.56.0, with your own numbers. A version check you can use in scripts:
python3 -c 'import sys; print("Python OK" if sys.version_info >= (3, 12) else "Please install Python 3.12+")'Python OKOn Windows the command may be
pythonorpyrather thanpython3. If typingpythonopens the Microsoft Store, Windows is using a placeholder ("app execution alias"): install Python properly, or turn the alias off under Settings → Apps → Advanced app settings → App execution aliases.
Virtual environments with venv and pip
If every project installs packages into one shared Python, sooner or later project A needs requests 2.34 while an old project B breaks with it. A virtual environment is a folder holding a private set of packages for one project, linked to a Python interpreter. Create one called .venv (the conventional name) inside the project, and activate it:
mkdir -p ~/projects/hello-ai
cd ~/projects/hello-ai
python3 -m venv .venv
source .venv/bin/activate
command -v python
python -c 'import sys; print("inside a venv:", sys.prefix != sys.base_prefix)'/home/nadia/projects/hello-ai/.venv/bin/python
inside a venv: TrueActivating does nothing magical: it puts .venv/bin at the front of your PATH — the trick from the previous section — so python and pip now mean the ones inside .venv. Your prompt usually shows (.venv) as a reminder. Now install packages into it. Use python -m pip rather than bare pip, so pip installs into exactly the Python you are running:
python -m pip install -q requests python-dotenv
python -m pip freeze > requirements.txt
cat requirements.txtcertifi==2026.7.22
charset-normalizer==3.5.2
idna==3.20
python-dotenv==1.2.4
requests==2.34.2
urllib3==2.8.0pip freeze lists every installed package with its exact version, including the ones requests pulled in by itself (certifi, idna, urllib3, charset-normalizer). Saved as requirements.txt and committed with the code, it lets anyone rebuild the same environment:
python -m pip install -q -r requirements.txtWhen you are done, deactivate takes .venv/bin off the PATH again (you will do that in a moment). The .venv folder itself is never shared or committed — it can be hundreds of megabytes and only works on the machine that made it. Delete it any time and recreate it from requirements.txt.
| Task | bash (Linux, macOS, WSL) | Git Bash on Windows | PowerShell |
|---|---|---|---|
| Activate the venv | source .venv/bin/activate | source .venv/Scripts/activate | .venv\Scripts\Activate.ps1 |
| Set a variable | export MODEL_NAME=practice-llm-1 | same as bash | $env:MODEL_NAME = "practice-llm-1" |
| Read a variable | echo "$MODEL_NAME" | same as bash | echo $env:MODEL_NAME |
| List all | env | env | Get-ChildItem Env: |
If PowerShell refuses to run Activate.ps1 ("running scripts is disabled on this system"), allow local scripts once with Set-ExecutionPolicy -Scope CurrentUser RemoteSigned.
Secrets in a .env file
Typing export lines every time you open a terminal gets old fast. The common solution for local development is a .env file in the project folder, one NAME=value per line, loaded by the python-dotenv package you just installed. Create it, and a small program that reads its settings:
cd ~/projects/hello-ai
cat > .env <<'EOF'
# Local settings for hello-ai. Never commit this file.
LLM_API_KEY=pk-practice-1234567890abcdef
MODEL_NAME=practice-llm-1
TEMPERATURE=0.2
EOF# file: settings_demo.py
import os
from dotenv import load_dotenv
load_dotenv() # reads .env; variables that are already set win
model = os.getenv("MODEL_NAME", "practice-llm-1")
temperature = float(os.getenv("TEMPERATURE", "0.7"))
api_key = os.environ["LLM_API_KEY"]
print(f"model={model} temperature={temperature}")
print(f"api key: {api_key[:3]}...{api_key[-4:]} ({len(api_key)} characters)")source .venv/bin/activate
python settings_demo.py
MODEL_NAME=bigger-model python settings_demo.py
deactivatemodel=practice-llm-1 temperature=0.2
api key: pk-...cdef (28 characters)
model=bigger-model temperature=0.2
api key: pk-...cdef (28 characters)Three things to notice:
- The program never prints the whole key, only enough to recognise it. Logs end up in many places (terminals, log services, screenshots in chat); a full key in a log is a leaked key.
- A variable that is already set in the real environment wins over
.env(that is python-dotenv's default). So.envis for your laptop; on a server or in Docker you set real environment variables, and the same code picks them up. .envmust never reach Git or GitHub. .gitignore: Keeping Secrets and Junk Out shows how to make Git ignore it, and how to share a.env.examplewith the variable names but no values.
uv: the modern way to manage a project
uv (from Astral, the makers of the Ruff linter) does the jobs of venv, pip and more in one fast tool, and it is what FastAPI's own documentation uses. It manages a project through pyproject.toml, the standard file where a Python project declares its name, Python version and dependencies. Install it once:
curl -LsSf https://astral.sh/uv/install.sh | shOn Windows use winget install --id astral-sh.uv -e (or powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"). Open a new terminal and uv --version should print a version (0.13 at the time of writing; uv is still 0.x, so its version is worth pinning in CI). Now create a project:
cd ~/projects
uv init --no-package hello-uv
cd hello-uv
ls -aInitialized project `hello-uv` at `/home/nadia/projects/hello-uv`
.
..
.git
.gitignore
.python-version
README.md
main.py
pyproject.tomluv init wrote a starter main.py, a README.md, a pyproject.toml, a .python-version file naming the Python version to use, and it even ran git init for you (.git, .gitignore) — you will learn what those are on the next page. --no-package asks for a plain application you run with main.py; without it, uv 0.13 sets the project up as an installable package with its code under src/, which is what you want for a library but more than a small app needs. Add packages with uv add:
uv add -q requests python-dotenv
cat pyproject.toml
ls -a[project]
name = "hello-uv"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"python-dotenv>=1.2.4",
"requests>=2.34.2",
]
.
..
.git
.gitignore
.python-version
.venv
README.md
main.py
pyproject.toml
uv.lockOne command created .venv (no activation needed), installed the packages, wrote them into pyproject.toml with a minimum version, and recorded the exact version of every package, including the indirect ones, in uv.lock. The requires-python line records the Python version uv found; on your machine it will likely say 3.14. uv run runs a command inside the project's environment, syncing it first if anything is missing:
uv run main.py
uv run python -c 'import requests; print("requests", requests.__version__)'Hello from hello-uv!
requests 2.34.2A teammate who clones the project runs uv sync and gets exactly the versions in uv.lock. Commit pyproject.toml and uv.lock; never commit .venv.
| Task | venv + pip | uv |
|---|---|---|
| Start a project | mkdir + python -m venv .venv | uv init name |
| Add a package | python -m pip install requests | uv add requests |
| Add a development-only tool | (a separate requirements file) | uv add --dev pytest |
| Record exact versions | pip freeze > requirements.txt | automatic: uv.lock |
| Recreate the environment | python -m pip install -r requirements.txt | uv sync |
| Run a script | activate, then python app.py | uv run app.py |
Which should you use? Learn both. venv and pip come with Python, every tool and tutorial understands them, and the earlier courses used them. uv is faster, keeps a proper lock file and is the default in new projects (OpenAI announced in March 2026 that it is acquiring Astral and committed to keeping uv open source). From Your First FastAPI App on, this course shows uv first with the pip equivalent beside it. Within one project, pick one and stick to it.
A project folder that scales
A layout that works for most small AI backends, and the one this course grows into:
hello-ai/
├── .venv/ the virtual environment (never committed)
├── .env real settings and secrets (never committed)
├── .env.example variable names, no values (committed)
├── .gitignore what Git should not track
├── pyproject.toml project and dependencies (or requirements.txt)
├── uv.lock exact versions (committed)
├── README.md what it is and how to run it
├── app/ the application code
│ └── main.py
├── tests/ automated tests
├── data/ datasets (usually not committed)
└── notebooks/ experimentsKeep code, configuration and data apart, keep secrets only in the environment, and make every project reproducible from what is committed. Those three habits carry straight into Docker and deployment at the end of this course.
Where this shows up in AI and backend work
- LLM API keys (OpenAI, Anthropic, Gemini) are read from environment variables by the official SDKs, for example
OPENAI_API_KEYandANTHROPIC_API_KEY. - Twelve-factor configuration: the same image runs in development, staging and production; only the environment differs (database URL, model name, log level).
- Reproducible experiments: a lock file records which versions of scikit-learn or PyTorch produced a result, so you can reproduce it months later.
- Hosting platforms (Render, Cloud Run, GitHub Actions) all have a "secrets" or "environment variables" screen that feeds exactly these variables to your app.
Common mistakes
- Installing into the wrong Python.
pip installwithout an active venv installs somewhere else, and thenimport requestsfails withModuleNotFoundError. Activate the venv (or useuv run), and check withcommand -v python. - Spaces around
=.export MODEL_NAME = xis an error in bash. Writeexport MODEL_NAME=x. - Forgetting that values are strings.
os.getenv("MAX_TOKENS")is"256", not256, andos.getenv("DEBUG")is"false"— which is a non-empty string and therefore true in anif. Convert explicitly. - Hard-coding or committing secrets. A key in
main.pyor in a committed.envis public the moment you push. Keep it in.env, ignore that file, and rotate any key that leaked. - Committing
.venv. It is large and machine-specific. Commitrequirements.txtorpyproject.toml+uv.lockinstead.
Try it yourself
- Easy: Export a variable
BATCH_SIZE=32and print twice its value from Python (careful: it arrives as text). - Medium: In
~/projects/hello-ai, create.env.examplefrom.envwith every value removed (keep the names and the comment), using onesedcommand:sed 's/=.*/=/'. - Hard: In the
hello-uvproject, add pytest as a development dependency and show the part ofpyproject.tomlwhere uv recorded it. Then runuv run pytest --version.
Answers
1. Convert with int() before doing arithmetic; without it, "32" * 2 would be "3232":
export BATCH_SIZE=32
python3 -c 'import os; print(int(os.environ["BATCH_SIZE"]) * 2)'642. sed replaces everything from the first = to the end of each line; the comment line has no = and is kept:
cd ~/projects/hello-ai
sed 's/=.*/=/' .env > .env.example
cat .env.example# Local settings for hello-ai. Never commit this file.
LLM_API_KEY=
MODEL_NAME=
TEMPERATURE=3. --dev puts the package in a dev dependency group, which is installed for development but left out of production installs:
cd ~/projects/hello-uv
uv add -q --dev pytest
tail -n 4 pyproject.toml
uv run pytest --version[dependency-groups]
dev = [
"pytest>=9.1.1",
]
pytest 9.1.1Summary
- Environment variables are text settings a program inherits;
export NAME=valuesets one,$NAMEreads it in bash,os.environ/os.getenvin Python. PATHis the list of folders the shell searches for programs; installers and venv activation work by changing it.command -vshows what runs.- Keep secrets in
.env, load them with python-dotenv, never print or commit them; real environment variables win, which is how servers configure the same code. - A virtual environment gives each project its own packages:
python -m venv .venv, activate,python -m pip install,pip freeze > requirements.txt. - uv does it all in one tool:
uv init,uv add,uv run, with dependencies inpyproject.tomland exact versions inuv.lock.
Next: Version Control and Your First Repository introduces Git: you will configure it, turn a project folder into a repository and make your first commit.

