DCubes
Python module

Lesson 3

Virtualenvs and pip

Isolate project dependencies with venv, install packages, and freeze requirements.

beginner30 minRun on your machine

What you will be able to do

  • Create and activate a virtual environment in the lab folder
  • Install a package with python -m pip and import it
  • Write a requirements.txt with pip freeze

Why this matters for data work

Global installs turn every project into a dependency lottery. One venv per project pins pandas, psycopg, and httpx to versions that match the job. Production images copy the same idea: isolated site-packages, not “whatever was on the laptop.”

Concepts

venv — a directory (often .venv) with its own python and pip. Create with python3 -m venv .venv.

Activate — puts that venv’s bin (or Scripts on native Windows) first on PATH. Your prompt often shows (.venv).

python -m pip — run pip as that interpreter’s module so you never upgrade the wrong pip.

requirements.txt — a list of packages (and often versions) another machine can install with pip install -r requirements.txt.

Never commit secrets into requirements. Pins only.

Practice on your machine

cd ~/dcubes/python-lab
python3 -m venv .venv

Activate (Linux, macOS, WSL):

source .venv/bin/activate

Your prompt should show (.venv). Check:

which python
python --version
python -m pip --version

which python should point inside ~/dcubes/python-lab/.venv/.

Install a tiny package used only for this lesson:

python -m pip install --upgrade pip
python -m pip install rich
python -c "import rich; print(rich.__version__)"

Freeze what you have (we will trim this later for real projects):

python -m pip freeze > requirements.txt
head -n 5 requirements.txt

Deactivate when you leave the project:

deactivate
which python

which python should no longer be the venv path. Reactivate with source .venv/bin/activate whenever you return.

What you should see

  • .venv/ directory in the lab.
  • After activate, which python under .venv.
  • rich imports and prints a version.
  • requirements.txt lists installed distributions.

Common mistakes

  • pip install without activating (or without python -m pip). Packages land on the system Python and vanish in the next venv.
  • Committing .venv/ to git. Later Git module: ignore it; commit requirements.txt only.
  • One mega-venv for every tutorial. Prefer a venv per lab or per project.
  • Forgetting to reactivate in a new terminal tab.

Next

Types and collections