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
- What command creates a venv using the standard library?
- How do you record the exact versions of installed packages?
Show answers
python -m venv .venv
pip freeze > requirements.txt
Exercises
- Create a venv and install
requests
andrich
. Freeze torequirements.txt
. - Deactivate the environment and confirm that
python
andpip
now point to your system versions.