logo
40

Pip & Virtual Environments

⏱️ 25 min

pip & virtualenv: Controllable Dependencies, Reproducible Environments

What might confuse you right now

"It works on my machine. Why bother with virtual environments?"

Because project A needs v1 and project B needs v2 -- that's super common. Without isolation, you'll hit dependency conflicts constantly.

One-line definition

pip manages package dependencies. virtualenv/venv manages isolated project environments.

Real-life analogy

Different projects are like different kitchens. You can't mix up the seasoning versions.

Minimal runnable example

python3 -m venv .venv
source .venv/bin/activate
pip install requests
pip freeze > requirements.txt

Quick quiz (5 min)

  1. Create and activate a venv.
  2. Install 2 packages and export the dependency list.
  3. In a new directory, reproduce the environment using requirements.txt.

Quiz answer guidelines & grading criteria

  • Answer direction: working code that covers core conditions and edge inputs from the prompt.
  • Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): Clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.

Transfer task (homework)

Migrate one of your old projects to its own venv and add a requirements.txt.

Acceptance criteria

You can independently:

  • Isolate project dependencies
  • Export and restore dependencies
  • Avoid polluting the global environment

Common errors & debugging steps (beginner edition)

  • Can't understand the error: read the last line for the error type (e.g., TypeError, NameError), then trace back to the relevant code line.
  • Not sure about a variable's value: temporarily add print(variable, type(variable)) at key points to verify data matches expectations.
  • Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.

Common misconceptions

  • Misconception: All projects can share the global Python installation.
  • Reality: Environment isolation is basic engineering hygiene.