Code of the Day
AdvancedTooling & Packaging

Virtual environments and pip

Isolate each project's dependencies so they never collide.

PythonAdvanced8 min read
Recommended first
By the end of this lesson you will be able to:
  • Explain why per-project isolation matters
  • Create and activate a virtual environment
  • Install and pin dependencies with pip

Two projects on one machine often need different versions of the same library — and a single global install can't satisfy both. A gives each project its own isolated set of packages. This is the project-shape and configuration lessons applied to Python's ecosystem, and it's pure hands-on self-reliance.

Why isolation matters

Installing packages globally leads straight to "dependency hell": upgrading a library for project A silently breaks project B. A virtual environment is a self-contained folder with its own Python and its own packages, so each project's dependencies are independent and reproducible.

Create and activate one

The standard venv module ships with Python — no extra install:

python -m venv .venv          # create an environment in .venv/
source .venv/bin/activate     # activate it (Windows: .venv\Scripts\activate)
# your prompt now shows (.venv); python and pip point inside it
deactivate                    # leave it when done

While active, python and pip operate inside the environment, touching nothing global.

Installing and pinning with pip

installs packages from PyPI. Capture exactly what's installed so others (and your future self, and the deploy server) get an identical set:

pip install requests
pip freeze > requirements.txt   # record exact versions (the lockfile idea)
pip install -r requirements.txt # reproduce the environment elsewhere

requirements.txt is the reproducibility guarantee from the build-and-release lesson — same inputs, same environment, everywhere.

Do it yourself: always .gitignore the .venv/ folder — it's generated and machine-specific. Commit requirements.txt (or pyproject.toml, next), not the environment itself.

Where to go next

A requirements.txt is enough to run a project. To share one as an installable package, you need a bit more. Next: packaging with pyproject.

Finished reading? Mark it complete to track your progress.

On this page