Virtual environments and pip: installing packages
On your own computer you install packages with pip, into a virtual environment, so each project keeps its own packages at the versions it needs.
From here on the lessons run in a terminal on your computer, in an empty folder made for the project. The commands are shown for macOS and Linux, with a note where Windows differs.
Make a virtual environment
python3 -m venv .venv
source .venv/bin/activate
which pythonpython3 -m venv .venv creates a folder called .venv holding its own copy of Python and its own place for packages. source .venv/bin/activate switches this terminal to it, and which python shows that python now means the one inside .venv. On your computer the path starts with your project folder; it ends in .venv/bin/python either way.
python -m venv .venv, then .venv\Scripts\activate. Most terminals show (.venv) at the start of the prompt while it is active.Why not install everything once, for the whole computer? Two projects will one day need different versions of the same package. With an environment each, both work. Delete the .venv folder and the project's packages are gone, with nothing else touched.
Install a package
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet pydantic==2.12.5
python -c "import pydantic; print(pydantic.VERSION)"pip install downloads a package and the packages it needs. ==2.12.5 pins an exact version, and --quiet hides the download progress. python -c runs one line of Python, here to prove the import works.
Writing down what is installed
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet pydantic==2.12.5
pip freeze > requirements.txt
cat requirements.txtpip freeze lists every installed package with its exact version, and > writes that list into requirements.txt instead of the screen. Pydantic brought four packages with it.
Commit requirements.txt with your code and leave .venv out. Anyone setting the project up runs pip install -r requirements.txt inside their own environment and gets the same versions.
- Run
deactivate, thenwhich pythonagain. - Install
pytestas well; the next lesson needs it. - Run
pip listand compare it withpip freeze.
This is what real progress feels like.