Why Virtual Environments Matter
Without virtual environments: Project A needs requests 2.0, Project B needs requests 3.0 β they cannot coexist in global pip. Virtual environments give each project its own isolated space.
# Without venv (global):
# pip install django==3.2 β breaks Project B which needs django==4.2
# With venv:
# project_a/venv/ β django 3.2 installed here
# project_b/venv/ β django 4.2 installed here
# Zero conflict!Creating a Virtual Environment
Use Python's built-in venv module. Create one per project.
# Create virtual environment (from project root)
python -m venv venv # Windows
python3 -m venv venv # macOS/Linux
# This creates:
# venv/
# bin/python (or Scripts\python.exe on Windows)
# bin/pip
# lib/ β installed packages go hereActivating and Deactivating
Always activate before working on a project.
# Activate:
# Windows (Command Prompt):
venv\Scripts\activate
# Windows (PowerShell):
venv\Scripts\Activate.ps1
# macOS / Linux:
source venv/bin/activate
# Prompt changes to show (venv) prefix
# (venv) $ pip install requests β installs ONLY in this env
# Deactivate when done:
deactivateYour prompt shows (venv) when a virtual environment is active. If you don't see it, you're installing into the global Python.
Installing and Managing Packages
Install packages with pip after activating your venv.
# Activate first, then:
pip install requests flask
pip install pandas==2.0.0 # specific version
# See what's installed:
pip list
pip show requests # details about one package
# Save your dependencies:
pip freeze > requirements.txt
# Reproduce on another machine:
pip install -r requirements.txtNever Commit the venv Folder
Add venv/ to .gitignore. Teammates recreate it from requirements.txt.
# .gitignore
venv/
__pycache__/
*.pyc
.env
*.egg-info/
dist/
build/
# Teammate setup:
git clone your-repo
cd your-repo
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt