Python Virtual Environments Explained

Understand what virtual environments are, why they matter, and how to use them in your Python projects.

The Problem

Imagine you have two Python projects:

  • Project A needs requests version 2.28
  • Project B needs requests version 2.31

If you install packages globally, you can only have one version at a time. This causes conflicts.

What Is a Virtual Environment?

A virtual environment is an isolated Python installation. Each project gets its own set of packages, independent of every other project on your machine.

my-project/
├── venv/              ← isolated Python + packages
├── src/
│   └── app.py
└── requirements.txt

Creating a Virtual Environment

Python’s built-in venv module handles everything:

# Create a virtual environment
python -m venv venv

# Activate it (macOS/Linux)
source venv/bin/activate

# Activate it (Windows)
venv\Scripts\activate

Once activated, your terminal prompt changes to show the environment name:

(venv) $ python --version
Python 3.12.0

Installing Packages

With the environment active, pip install puts packages inside the venv/ directory, not globally:

(venv) $ pip install requests==2.31.0
(venv) $ pip install flask

Freezing Dependencies

Record your exact package versions so others can reproduce your environment:

(venv) $ pip freeze > requirements.txt

This creates a file like:

flask==3.0.0
requests==2.31.0
Werkzeug==3.0.1

Others can recreate your environment with:

python -m venv venv
source venv/bin/activate
pip install -r requirements.txt

Deactivating

When you are done working on the project:

(venv) $ deactivate
$

The Golden Rule

Never install project packages globally. Always create a virtual environment first. This prevents version conflicts and makes your projects reproducible.

# Starting a new project - always do this first
mkdir my-project && cd my-project
python -m venv venv
source venv/bin/activate