Virtual Environments
venv
Learn why Python projects use isolated environments to manage dependencies, prevent conflicts, and keep your system clean.
What Is a Virtual Environment?
A virtual environment is a self-contained directory that holds its own Python interpreter and its own set of installed packages: completely independent from your system-wide Python installation.
Why Do We Need Them?
The Dependency Problem
Every Python package can depend on other packages, each at specific versions. When two projects require different versions of the same package, a conflict arises:
Anatomy of a venv
The Golden Rule of venv
How Isolation Works
venv vs. Other Approaches
| venv | virtualenv | conda | |
|---|---|---|---|
| Built-in? | ✓ Yes (Python 3.3+) | ✕ Separate install | ✕ Separate install |
| Speed | Fast | Very fast | Slower |
| Non-Python deps | ✕ | ✕ | ✓ (C libs, etc.) |
| Best for | Most projects | Legacy Python | Data science |
How to Create and Use a venv
Example: Creating a venv
Example: Installing Packages
Example: Freezing Dependencies
The Full Workflow
What Not to Do with .venv
Summary: Key Concepts
| Concept | Details |
|---|---|
| Virtual Environment | Isolated directory with its own Python + packages |
| Create Command | python3 -m venv .venv |
| Activate (Unix) | source .venv/bin/activate |
| Activate (Windows) | .venv\Scripts\activate |
| Freeze Deps | pip freeze > requirements.txt |
| Restore Deps | pip install -r requirements.txt |
| Deactivate | deactivate |
| Git Rule | Commit requirements.txt, not .venv/ |
Question 1 of 5
What is the primary purpose of a Python virtual environment?
Question 2 of 5
Which command creates a virtual environment named .venv using the built-in venv module?
Question 3 of 5
What does activating a virtual environment actually do behind the scenes?
Question 4 of 5
Which file should you commit to version control so teammates can recreate your environment?
Question 5 of 5
Why should you never move a .venv directory to a different location after creating it?