Lesson 44 of 52Real projects
Virtual Environments
Isolate each project's dependencies with venv or uv, pin them with lock files, and never break your system Python.
Project A needs Django 4.2. Project B needs Django 5.2. Your laptop has one Python. Without isolation, installing for one breaks the other, and "works on my machine" becomes a daily problem. Virtual environments give every project its own private set of packages. Using them properly is the first thing a reviewer checks in a repo, and it is the basis of every Dockerfile and CI pipeline you will write.
The problem: one shared site-packages
When you pip install requests, the package is copied into a folder called site-packages that belongs to one Python installation. If every project installs into the same Python, they all share that folder, and only one version of each package can live there.
Worse, on macOS and Linux the system Python is used by the operating system itself. Installing into it with sudo pip install can overwrite packages the OS depends on. Modern Linux distributions now block this outright with an "externally-managed-environment" error, for good reason.
A virtual environment is a folder
A virtual environment (venv) is a folder containing a small Python launcher that points back to a base interpreter, plus its own empty site-packages. Packages you install while it is active go there and nowhere else.
You install Python once (or let uv manage versions).
The classic workflow: venv and pip
venv ships with Python. The convention is to name the folder .venv in the project root, and to add it to .gitignore: it is rebuilt from your dependency list, never committed.
cd shoppython3 -m venv .venv # create the environmentsource .venv/bin/activate # macOS / Linux.venv\Scripts\activate # Windows (PowerShell / cmd)which python # now .../shop/.venv/bin/pythonpip install "fastapi[standard]" httpxpip freeze > requirements.txt # record exact versionsdeactivate # back to normalActivating only changes your shell's PATH so that python and pip mean the ones inside .venv. You can skip activation entirely by calling them by path: .venv/bin/python -m pytest.
Always prefer python -m pip install ... over a bare pip when in doubt. It guarantees pip installs into the same Python you are about to run.
You can check from inside Python whether you are in a venv: sys.prefix is the environment's folder, and sys.base_prefix is the original installation.
Press Run (⌘ Enter) to see what happens.source .venv/bin/activate actually do?Recording dependencies
Your teammates, CI and Docker image must install the same packages. There are two layers to record:
- What you depend on directly, with loose ranges:
fastapi>=0.115,httpx. You edit this by hand. - The exact resolved versions of everything, including dependencies of dependencies:
starlette==0.46.2,anyio==4.9.0, ... This is the lock file. Tools generate it.
| File | Role |
|---|---|
requirements.txt | The old, simple format: one requirement per line. Often holds pip freeze output, which mixes direct and indirect deps. |
pyproject.toml | The modern standard project file. Lists direct dependencies under [project] dependencies. |
uv.lock (or poetry.lock) | The lock file: exact versions and hashes of every package, for reproducible installs. Commit it. |
# direct dependencies
fastapi[standard]>=0.115
httpx==0.28.1
sqlalchemy>=2.0,<3A version specifier says which versions are acceptable: == pins one exact version, >= sets a minimum, <3 keeps you below a breaking major version, and ~=2.0 means "compatible release" (>=2.0, <3). Version numbers are compared part by part as numbers, not as text:
Press Run (⌘ Enter) to see what happens.Match each specifier to what it allows.
uv: the modern default
uv is a Python package and project manager written in Rust. It replaces pip, venv, pip-tools, pipx and even pyenv with one fast tool, often 10 to 100 times faster than pip. In 2026 it is the default choice for new projects.
curl -LsSf https://astral.sh/uv/install.sh | sh # install uv onceuv init shop && cd shop # creates pyproject.toml, .python-version, main.pyuv add fastapi httpx # adds to pyproject.toml, updates uv.lock, installs into .venvuv add --dev pytest ruff # development-only dependenciesuv run python main.py # runs inside the project's .venv (creates/syncs it if needed)uv run pytestuv sync # make .venv match uv.lock exactly (what CI does)uv lock --upgrade-package httpx # move one package to a newer versionuv python install 3.13 # uv can even install Python versionsYou rarely activate anything with uv: uv run always uses the right environment. A teammate clones the repo, runs uv sync, and gets byte-for-byte the same packages as you, because uv.lock is committed. If you need the old style, uv venv creates a .venv and uv pip install -r requirements.txt works as a fast drop-in for pip.
Order a new teammate's first run of an existing uv project.
- Tap the steps below in the right order.
Tools that are not project dependencies: pipx and uv tool
Command-line tools you use across all projects (ruff, httpie, cookiecutter) should not live in any one project's venv, and definitely not in the system Python. Install them with pipx or uv tool, which give each tool its own hidden venv and put the command on your PATH.
uv tool install ruff # or: pipx install ruffruff --versionuvx cowsay -t "hi" # run a tool once without installing itpip install httpx fails with an externally-managed-environment error. What should you do?Parse a requirements file
Write parse_requirements(text) that reads the contents of a requirements.txt and returns a dict mapping each normalised package name to its version specifier.
Rules:
- Skip blank lines and comment lines. A
#also starts a comment at the end of a line. - Skip option lines that start with
-(like-r base.txtor--index-url ...). - Drop environment markers: everything from
;onwards. - Drop extras in square brackets:
fastapi[standard]is the packagefastapi. - Normalise names: lowercase, and turn
_and.into-(soTyping_Extensionsbecomestyping-extensions). - The specifier is the rest of the requirement with all spaces removed, or
""if there is none.
text = """
# web
fastapi[standard] >= 0.115
httpx==0.28.1 # pinned
Typing_Extensions
-r dev.txt
"""
parse_requirements(text)
# {"fastapi": ">=0.115", "httpx": "==0.28.1", "typing-extensions": ""}- virtual environment
- A folder with its own interpreter launcher and
site-packages, isolating one project's packages. - site-packages
- The folder where installed third-party packages live for a given Python or venv.
- lock file
- A generated file (
uv.lock) pinning the exact version of every direct and indirect dependency. - version specifier
- A rule like
>=2.0,<3saying which versions of a package are acceptable. - uv
- A fast all-in-one Python project manager: venvs, installs, lock files, tools and Python versions.
- pipx / uv tool
- Install command-line tools globally, each in its own isolated environment.