Virtual Environments¶
A virtual environment is an isolated Python installation. Each project gets its own set of packages, so they don't conflict with each other.
Learn Your Way¶
| Read | Build | Watch | Test | Review | Visualize |
|---|---|---|---|---|---|
| You are here | Projects | Videos | Quiz | Flashcards | Diagrams |
Visualize It¶
See how Python finds packages via sys.path — the key to understanding environments:
Open in Python Tutor
Why virtual environments matter¶
Without virtual environments:
With virtual environments:
Project A → .venv/ → requests 2.28 (isolated)
Project B → .venv/ → requests 2.31 (isolated)
→ Both work fine!
Creating a virtual environment¶
# Navigate to your project folder.
cd my_project
# Create a virtual environment named ".venv".
python -m venv .venv
This creates a .venv/ folder containing a private copy of the Python interpreter and pip.
Activating it¶
You must activate the environment before using it:
# macOS / Linux
source .venv/bin/activate
# Windows (Command Prompt)
.venv\Scripts\activate
# Windows (PowerShell)
.venv\Scripts\Activate.ps1
# Windows (Git Bash)
source .venv/Scripts/activate
When activated, your terminal prompt changes:
Installing packages¶
With the environment activated, pip installs packages into .venv/ only:
requirements.txt¶
Save your project's dependencies:
# Save current packages.
pip freeze > requirements.txt
# Install from requirements file (on another machine or in CI).
pip install -r requirements.txt
Example requirements.txt:
Deactivating¶
The workflow¶
Every time you start a new project:
# 1. Create the project folder.
mkdir my_project && cd my_project
# 2. Create a virtual environment.
python -m venv .venv
# 3. Activate it.
source .venv/bin/activate # or .venv\Scripts\activate on Windows
# 4. Install packages.
pip install requests flask
# 5. Save dependencies.
pip freeze > requirements.txt
# 6. Work on your project...
# 7. When done, deactivate.
deactivate
.gitignore¶
Never commit the .venv/ folder to git. Add it to .gitignore:
Other developers recreate it from requirements.txt.
Common mistakes¶
Installing globally:
Always check your prompt for(.venv) before installing.
Committing .venv to git:
The .venv/ folder is large and machine-specific. Only commit requirements.txt.
Wrong Python version:
Practice¶
- Expansion Modules
- Level 2 / 03 Data Cleaning Pipeline
- Level 2 / 15 Level2 Mini Capstone
- Level 3 / 10 Dependency Boundary Lab
- Level 6 / 11 Dead Letter Row Handler
- Level 6 / 15 Level6 Mini Capstone
- Level 7 / 08 Ingestion Observability Kit
- Level 9 / 08 Change Impact Analyzer
- Module: 04 Fastapi Web / 03 Database Backed
- Module: 07 Data Analysis / 05 Analysis Report
- Module: 09 Docker Deployment / 01 First Dockerfile
Quick check: Take the quiz
Review: Flashcard decks Practice reps: Coding challenges
| ← Prev | Home | Next → |
|---|---|---|