Setting Up: Virtual Environments and pip
Give every project its own clean, isolated set of packages
pip is the tool that installs those packages, and requirements.txt records exactly what a project needs so anyone can rebuild it.- explain why global installs cause dependency conflicts,
- create and activate a virtual environment with
python -m venv, - install, inspect and remove packages with
pip, - freeze a project into
requirements.txtand rebuild it elsewhere, - read version specifiers like
==,>=and~=.
1. The problem: one Python, many projects
When you run pip install without any setup, the package goes into the global site-packages folder shared by every project on your machine. That feels convenient until two projects disagree. Imagine an old website that only runs on django==3.2 and a new one that needs django==5.0. There is only one global slot for Django, so installing one version breaks the other. This is a dependency conflict.
Global installs cause other pain too: you cannot tell which packages a given project actually uses, you often need administrator rights to install system-wide, and a change made for one project can silently break another months later. The fix is isolation: give each project its own private set of packages.