Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

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

Example
python3 -m venv .venv
source .venv/bin/activate
which python

python3 -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.

On Windows
Use 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

Example
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

Example
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet pydantic==2.12.5
pip freeze > requirements.txt
cat requirements.txt

pip 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.

Try it yourself
  • Run deactivate, then which python again.
  • Install pytest as well; the next lesson needs it.
  • Run pip list and compare it with pip freeze.

This is what real progress feels like.