Virtual Environments and pip: Stopping Projects From Breaking Each Other
Why installing Python packages globally causes chaos, and how python3 -m venv plus pip give every project its own clean sandbox.
You'll learn why global pip install breaks older projects, how to create and activate an isolated .venv folder for each project, and how requirements.txt makes setups reproducible. Assumes Python 3 installed and a terminal.
1. The dependency collision problem
Suppose Project A uses requests version 1.x. Six months later you start Project B and run pip install requests, upgrading it to version 2.x. Now Project A crashes because a function it relied on was renamed.
A virtual environment (venv) fixes this by giving every project its own private .venv folder with its own copy of python and its own installed packages. Project A and Project B never touch each other.
2. Create and activate .venv
Inside your project folder, run:
mkdir my-project && cd my-project
python3 -m venv .venvNow activate it so your terminal uses .venv's Python instead of your system Python:
# macOS / Linux:
source .venv/bin/activate
# Windows PowerShell:
# .venv\Scripts\Activate.ps1Your terminal prompt will change to show (.venv) at the front. While .venv is active, python and pip point inside .venv.
Run which python (or Get-Command python on Windows) while .venv is active—the path should end inside .venv/.
3. Installing and sharing with requirements.txt
pip install httpx
pip freeze > requirements.txtrequirements.txt is a tiny text list of every installed package and its exact version. Anyone else can recreate your exact environment in two commands:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtImportant: Add .venv/ to your .gitignore file so you never commit thousands of library files to Git—commit requirements.txt instead.
Common mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
ModuleNotFoundError after pip install | Forgot to activate .venv (or editor uses wrong interpreter) | Activate .venv and run python -m pip install ... |
externally-managed-environment on Linux | OS blocks global pip install | Create and activate .venv first |
Committed .venv/ to Git | Pushed 5,000+ package files | Add .venv/ to .gitignore |
Practice
- Which file should you commit to Git:
.venv/orrequirements.txt?
Answer: requirements.txt.
What you learned
- Create an isolated environment per project with
python3 -m venv .venv. - Activate
.venvbefore runningpip install ...orpython. - Save dependencies to
requirements.txtwithpip freeze > requirements.txtand keep.venv/out of Git.