Python Virtual Environments
A virtual environment is an isolated Python installation with its own packages, so each project gets the exact dependency versions it needs without conflicting with other projects or the system Python.
WHY IT EXISTS Python installs packages into a shared location by default, so two projects on one machine must share the same versions of every library. That breaks down quickly: one project needs an old version of a framework, another needs a new one, and a single global install cannot satisfy both. Virtual environments exist to give each project its own isolated set of dependencies.
THE MENTAL MODEL Think of a virtual environment as a sandbox folder that contains its own copy or link of the Python interpreter and its own package directory. When the environment is active, Python and pip look inside that sandbox instead of the global installation, so anything you install stays local to that project and disappears in scope when you deactivate.
HOW IT WORKS Creating an environment, typically with the built-in venv module, makes a directory with a pointer to a Python interpreter and an empty site-packages folder. Activating it adjusts your shell so that python and pip resolve to the environment's versions, usually by prepending its path. Packages you install with pip then land in that folder only. Recording exact versions in a requirements file, often produced with pip freeze, lets anyone recreate the same environment elsewhere by installing from that file into a fresh environment. Deactivating returns you to the system Python.
WHEN IT MATTERS Use a virtual environment for essentially every project beyond a throwaway script, especially when collaborating, deploying, or running multiple projects with differing dependencies. It matters most for reproducibility: a teammate or a production server can rebuild the identical dependency set. It also keeps the system Python clean, avoiding the permission issues and breakage that come from modifying global packages.
ONE CONCRETE EXAMPLE Suppose project A needs version 1 of a data library and project B needs version 2. You create a venv in project A, activate it, and pip install the version-1 library; it lands only in A's folder. You do the same in project B with version 2. Each project runs with its required version, neither interferes with the other, and pip freeze in each produces a requirements file so a colleague can reproduce both setups exactly on a different machine without any conflict.
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.