Python Virtual Environments Explained
Everyone tells you to 'use a virtual environment' but rarely what one is. It's simpler than it sounds — a private box of packages for one project. Here's the whole idea in five minutes.
Every Python tutorial tells you to "create a virtual environment first," then moves on without saying what one is. So it stays a magic incantation. It isn't — it's one of the most useful ideas in Python, and it takes about five minutes to actually get.
The problem: one shared Python
Install Python and you get a single, system-wide set of packages. Now imagine two projects: one needs version 1 of a library, the other needs version 2. Install one and you break the other. There's only one shelf, and both projects are fighting over it.
What a virtual environment is
A virtual environment is a private, per-project copy of that shelf. It's a folder holding its own Python interpreter link and its own site-packages directory. Packages you install while it's active go there, not into the system Python — so each project gets exactly the versions it wants, isolated from every other.
python3 -m venv .venv # create the box (a .venv/ folder)
source .venv/bin/activate # step into it — prompt shows (.venv)
pip install requests # lands in .venv, not system Python
deactivate # step back out
What "activate" actually does
Activating doesn't do anything mysterious — it just puts the environment's bin/ at the front of your PATH. So python and pip now resolve to the ones inside .venv. That's the whole trick: same command names, pointed at a different shelf.
A virtual environment is a sandbox for dependencies.
activateswaps which Python your shell reaches for;deactivateswaps it back. Nothing is installed globally, nothing collides.
Why you commit the list, not the folder
You don't check the .venv/ folder into Git — it's big and machine-specific. You record the list of what's in it so anyone can rebuild the same box:
pip freeze > requirements.txt # save the exact versions
pip install -r requirements.txt # recreate the box elsewhere
The mental model to keep
Picture one labelled box of packages per project, and a switch that points python at whichever box you're working in. Create a .venv for every project, activate it before you install anything, and the whole class of "it worked yesterday / on my machine" version problems quietly disappears.
Stop reading, start building
This pairs with a hands-on BytExplorer course — do it on your own machine and actually keep the skill.