Skip to content

Virtual Environments

Isolate project dependencies with venv, activate and deactivate, and manage multiple Python versions.

What you'll learn

  • Create a virtual environment with venv
  • Activate and deactivate environments
  • Understand why isolation matters
  • Use requirements.txt to pin dependencies
  • Manage multiple Python versions

Concept

Why Virtual Environments?

Without virtual environments, all your Python projects share the same global site-packages directory. If Project A needs Django 3 and Project B needs Django 4, they conflict. Virtual environments solve this by giving each project its own isolated Python environment with its own package directory.

A virtual environment is a self-contained directory containing:

  • A Python interpreter (symlink to a specific version)
  • Its own site-packages directory
  • Its own installed packages
  • Activation scripts

Creating a Virtual Environment

Use the built-in venv module (Python 3.3+):

# Create a virtual environment named 'venv' (or '.venv')
python -m venv venv

# Or specify a Python version
python3.11 -m venv venv

This creates a venv/ directory containing the isolated Python environment. The common convention is to name it .venv (with a dot) so it is hidden in file explorers, or venv (without a dot).

Activating

Activation modifies your shell's PATH so the virtual environment's Python and pip are used first:

# Windows (Command Prompt)
venv\Scripts\activate

# Windows (PowerShell)
venv\Scripts\Activate.ps1

# macOS / Linux
source venv/bin/activate

After activation, your prompt changes to show the environment name:

(venv) $ python --version
(venv) $ pip install django

Now python and pip refer to the virtual environment's versions, and installed packages go into venv/lib/site-packages/ instead of the global directory.

Deactivating

deactivate

This restores your shell to the global Python environment. The virtual environment still exists on disk — you can reactivate it anytime with the activate command.

requirements.txt

Pin your dependencies in a requirements.txt file so others can reproduce your environment:

# requirements.txt
django==4.2.7
requests>=2.31.0
numpy~=1.26.0
pytest==7.4.3

Install from it:

pip install -r requirements.txt

Generate it from your current environment:

pip freeze > requirements.txt

Pin exact versions (==) for reproducible builds. Use >= only if you intentionally want to allow upgrades. The ~= operator allows patch upgrades (e.g., ~=1.26.0 allows 1.26.x but not 1.27).

.gitignore

Never commit the virtual environment directory — it is platform-specific and large. Add it to .gitignore:

# .gitignore
venv/
.venv/
env/
__pycache__/

Commit requirements.txt instead — anyone can recreate the environment from it.

Multiple Python Versions

To manage multiple Python versions on one machine:

  • pyenv (macOS/Linux) — install and switch between Python versions
  • pyenv-win (Windows) — Windows port of pyenv
  • Official Python installer — install multiple versions side by side
# With pyenv
pyenv install 3.11.7
pyenv install 3.12.1
pyenv local 3.11.7   # set version for current directory

# Create a venv with a specific version
python3.11 -m venv venv311
python3.12 -m venv venv312

Modern Alternatives

  • poetry — dependency management and packaging in one tool
  • pipenv — Pipfile + Pipfile.lock for deterministic environments
  • uv — ultra-fast Rust-based replacement for pip and venv
  • conda — popular in data science, manages non-Python dependencies too

For beginners, venv + pip + requirements.txt is the standard starting point. Graduate to poetry or uv as your projects grow.

Example

              # --- Creating and using a virtual environment ---
# These are shell commands, not Python code:

# 1. Create the virtual environment
#    python -m venv .venv

# 2. Activate it
#    Windows:  .venv\Scripts\activate
#    macOS:    source .venv/bin/activate

# 3. Install packages (they go into .venv, not global)
#    pip install django requests

# 4. Save dependencies
#    pip freeze > requirements.txt

# 5. Deactivate when done
#    deactivate

# --- requirements.txt example ---
# django==4.2.7
# requests>=2.31.0,<3.0.0
# numpy~=1.26.0
# pytest==7.4.3

# --- .gitignore example ---
# .venv/
# venv/
# __pycache__/
# *.pyc

# --- Python code to check which environment you're in ---
import sys
import os

# Check if running in a virtual environment
in_venv = hasattr(sys, 'real_prefix') or (
    hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
)
print(f"Running in virtual environment: {in_venv}")
print(f"Python executable: {sys.executable}")
print(f"Prefix: {sys.prefix}")

# List installed packages
import subprocess
result = subprocess.run(
    [sys.executable, "-m", "pip", "list"],
    capture_output=True, text=True
)
print("Installed packages:")
print(result.stdout[:500])  # first 500 chars
            

Shows the full venv workflow: create, activate, install, freeze, deactivate. Includes a requirements.txt example, .gitignore entries, and Python code to detect and inspect the current virtual environment.

Try it

  • JSON Formatter

    Dependency files like pyproject.toml use structured formats — inspect them.

  • Case Converter

    Package and environment naming conventions.

Common mistakes

The mistake

Committing the virtual environment directory to version control

The fix

The venv directory is platform-specific, large, and not portable. Add 'venv/' and '.venv/' to .gitignore and commit requirements.txt instead. Anyone can recreate the environment with 'pip install -r requirements.txt'.

The mistake

Forgetting to activate the virtual environment before installing packages

The fix

If you run pip install without activating, packages go into the global Python environment, affecting all projects. Always activate first: check that your prompt shows (venv) before installing. Use 'which python' to verify you are using the venv's Python.

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors