Virtual Environments

An isolated Python installation with its own installed packages, kept separate from the system Python and from other projects.

Purpose

A virtual environment is a self-contained directory holding its own Python interpreter (or a link to one) and its own installed packages, entirely separate from the system-wide Python and from every other project’s environment.

Example

# Standard library tool, no install needed:
python -m venv .venv
source .venv/bin/activate      # macOS/Linux
.venv\Scripts\activate         # Windows

pip install requests           # installs only into this .venv, not system-wide
# This project's own tool, uv, does the equivalent in one step:
uv sync                        # creates .venv/ from pyproject.toml + lockfile automatically
uv add requests                # adds a dependency and updates the lockfile

Behavior notes

  • Without a virtual environment, pip install affects the system Python — shared by every project and, on some systems, the operating system’s own tooling. Two projects needing different versions of the same package can’t both be satisfied by one shared, global installation.
  • Activating an environment (source .venv/bin/activate) changes which python and pip the shell finds first, so commands run against that environment’s isolated packages without any special flags.
  • A pyproject.toml records a project’s declared dependencies; a lockfile (uv.lock, or requirements.txt in older pip-only workflows) records the exact resolved versions actually installed — the difference between “what this project needs” and “precisely what’s currently installed to satisfy that.”

Common mistakes

  • Running pip install without an active virtual environment and being surprised later when a different project’s dependencies conflict with it, or when the same package needs a different version somewhere else.
  • Committing a .venv/ directory to version control — it’s large, platform-specific, and fully reproducible from pyproject.toml plus a lockfile; it belongs in .gitignore, not the repo.
  • Installing a third-party package without checking it first: how actively maintained it is, how widely used, whether its license fits the project, and what it (and its own dependencies) can actually do once installed — a package runs with the same permissions as the rest of the program.

Implementation notes

Virtual environments and package isolation are a Python ecosystem convention, implemented by tooling (venv, pip, uv, and others) — not a language-level feature import itself is aware of.

Taught in these lessons

Related reference