Skip to main content

Virtual Environments (venv) in Python

When you build real-world Python applications, different projects often require different versions of the same library.

If you install everything globally on your operating system, updating a package for Project A can instantly break Project B.

To solve this, Python gives us Virtual Environments (venv) — isolated sandbox folders for each individual project.


1. The Real-World Conflict: Global vs Isolated

Global Python Installation (pip global)
├── Project A (requires requests v2.20) <── Dependency Conflict! 💥
└── Project B (requires requests v2.31) <── Dependency Conflict! 💥

With Virtual Environments:
├── Project A ── [venv A] ── requests v2.20 (Safe & Isolated) ✅
└── Project B ── [venv B] ── requests v2.31 (Safe & Isolated) ✅

2. Step-by-Step Setup Guide

Step 1: Create the Virtual Environment

Open your terminal inside your project folder and run:

python -m venv .venv

(This creates a local .venv folder containing a dedicated copy of Python and pip).


Step 2: Activate the Environment

You must activate the environment so terminal commands use this sandbox:

  • Windows (PowerShell):
    .\.venv\Scripts\Activate.ps1
  • Windows (Command Prompt):
    .\.venv\Scripts\activate.bat
  • macOS / Linux (Bash / Zsh):
    source .venv/bin/activate
Visual Confirmation

When activated, you will see (.venv) displayed at the start of your terminal line. Any package you install with pip now stays strictly inside this project!


Step 3: Deactivate When Finished

To return your terminal back to the standard global Python path, run:

deactivate

Quick Summary

  • Dependency Isolation: Virtual environments keep external packages separate per project, avoiding global version conflicts.
  • Creation: python -m venv .venv creates an isolated Python sandbox directory.
  • Activation: .\.venv\Scripts\activate (Windows) or source .venv/bin/activate (Mac/Linux).
  • Deactivation: deactivate exits the virtual environment back to global system Python.

What's Next?

Let's look at modern package management with pip, requirements.txt, and the ultra-fast tool uv in Managing Packages & Modern uv!