Skip to content

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.

14 min read0/4 questions

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.

One interpreter, isolated environments
project: shopproject: legacypython3.13: base interpreterpython3.13base interpretershop/.venv: own site-packagesshop/.venvown site-packagesdjango 5.2: + its depsdjango 5.2+ its depslegacy/.venv: own site-packageslegacy/.venvown site-packagesdjango 4.2: + its depsdjango 4.2+ its depssystem packages: used by the OSsystem packagesused by the OSpython -m venvpython -m venvpip installpip installsudo pip: no

You install Python once (or let uv manage versions).

1/4

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 normal

Activating 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.

Python
import sys print("running:", sys.executable)print("prefix:", sys.prefix)print("in a virtual environment:", sys.prefix != sys.base_prefix)print("version:", sys.version.split()[0])
Output
Press Run (⌘ Enter) to see what happens.
Quick check
What does source .venv/bin/activate actually do?
Need a nudge? A hint rules out a wrong answer.

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.
FileRole
requirements.txtThe old, simple format: one requirement per line. Often holds pip freeze output, which mixes direct and indirect deps.
pyproject.tomlThe 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.
requirements.txt
# direct dependencies
fastapi[standard]>=0.115
httpx==0.28.1
sqlalchemy>=2.0,<3

A 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:

Python
def parse(v): return tuple(int(p) for p in v.split(".")) print("2.10.0" > "2.9.0") # string compare: wrong!print(parse("2.10.0") > parse("2.9.0")) # numeric compare: rightprint(parse("0.115.0") >= parse("0.100"))
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/4 matched

Match each specifier to what it allows.

Choose an item, then its match on the other side.

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 versions

You 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.

Put it in order5 steps

Order a new teammate's first run of an existing uv project.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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 it
Quick check
pip install httpx fails with an externally-managed-environment error. What should you do?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

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.txt or --index-url ...).
  • Drop environment markers: everything from ; onwards.
  • Drop extras in square brackets: fastapi[standard] is the package fastapi.
  • Normalise names: lowercase, and turn _ and . into - (so Typing_Extensions becomes typing-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": ""}
Python
def parse_requirements(text: str) -> dict[str, str]: # Go line by line: strip comments and markers, then split name from specifier. pass
Key terms
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,<3 saying 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.