Course Progress67%
🍎 Python Practical Python Topic 67 / 100
⏳ 7 min read

Virtual Environments

Give every project its own isolated Python + packages with venv — no more version conflicts between projects.

"A virtual environment is a private Python installation just for one project. Project A can use Flask 2.0 while Project B uses Flask 3.0, and they never interfere."

— ShurAI

The Problem: Global Package Conflicts

Without virtual environments, all projects share the same Python installation. This causes conflicts:

⚠️ The version conflict problem:
Project A (old)
needs django==3.2
Project B (new)
needs django==5.0
You can only have one version installed globally. Install Django 5 and Project A breaks.

Virtual environments solve this by giving each project its own isolated Python + packages:

📁 project-a/venv/
django==3.2
requests==2.28.0
Only what A needs
📁 project-b/venv/
django==5.0
numpy==1.26.0
Only what B needs

Creating and Using a Virtual Environment

The whole workflow in four steps:

terminal — step 1: create the environment
python -m venv venv
# Creates a folder called 'venv' in your project directory
terminal — step 2: activate it
# Windows:
venv\Scriptsctivate

# Mac / Linux:
source venv/bin/activate

# Your prompt changes to show (venv) at the start
# (venv) $ _
terminal — step 3: install packages (only goes into this venv)
(venv) $ pip install requests pandas flask
terminal — step 4: deactivate when done
(venv) $ deactivate
# Back to your global Python
$

The Complete Project Workflow

✅ The right way to start every Python project:
1
mkdir my-project && cd my-project — create project folder
2
python -m venv venv — create virtual environment
3
source venv/bin/activate — activate it
4
pip install ... — install what you need
5
pip freeze > requirements.txt — save dependencies
6
Add venv/ to .gitignore — don’t commit the venv folder
⚠️ Never commit the venv folder to Git

The venv/ folder is large and machine-specific. Always add it to .gitignore. Your requirements.txt is what you share — others recreate the venv from it using pip install -r requirements.txt.

Quick Recap — venv Cheat Sheet

terminal — everything you need day-to-day
python -m venv venv          # create
source venv/bin/activate     # activate (Mac/Linux)
venv\Scriptsctivate        # activate (Windows)
pip install <package>        # install inside venv
pip freeze > requirements.txt # save list
deactivate                   # exit venv

"Rule: every project gets its own venv. No exceptions. It takes 10 seconds to set up and saves hours of 'why is this suddenly broken' debugging later."

— ShurAI

🧠 Quiz — Q1

What is the main problem that virtual environments solve?

🧠 Quiz — Q2

What command creates a virtual environment called venv in your current folder?

🧠 Quiz — Q3

How do you know a virtual environment is currently active?

🧠 Quiz — Q4

Why should you add venv/ to .gitignore?