Python - Virtual Environments

Overview

Estimated time: 25–35 minutes

Use virtual environments to isolate dependencies per project. This prevents version conflicts and keeps your global Python clean.

Learning Objectives

  • Create and activate a virtual environment on Windows, macOS, and Linux.
  • Install packages into a venv with pip and freeze them for reproducibility.
  • Understand when to use venv, virtualenv, or conda.

Prerequisites

Create and activate a venv

# Create
python -m venv .venv

# Activate
# macOS/Linux:
source .venv/bin/activate
# Windows (PowerShell):
.venv\\Scripts\\Activate.ps1

# Verify
python --version
pip --version

Install packages and freeze

pip install requests
pip list
pip freeze > requirements.txt

Common Pitfalls

  • Forgetting to activate the venv before installing requirements (packages go to the wrong place).
  • Using the wrong shell command for activation on Windows vs macOS/Linux.
  • Mixing conda envs with venv in the same project; pick one tool per project.

Checks for Understanding

  1. What command creates a venv using the standard library?
  2. How do you record the exact versions of installed packages?
Show answers
  1. python -m venv .venv
  2. pip freeze > requirements.txt

Exercises

  1. Create a venv and install requests and rich. Freeze to requirements.txt.
  2. Deactivate the environment and confirm that python and pip now point to your system versions.