Virtual Environments
Create isolated Python environments to avoid dependency conflicts
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
The problem: conflicting dependencies
Without a virtual environment, pip install puts packages in a single global location. Every project on your machine shares the same packages.
This causes conflicts. Project A needs requests==2.28. Project B needs requests==2.31. You can only have one version installed globally. Updating for Project B breaks Project A.
What a virtual environment does
A virtual environment is a self-contained directory that holds its own Python interpreter and its own set of packages. When you activate a virtual environment, pip install writes packages to that directory — not to the global location.
Each project gets its own environment. Project A has its packages. Project B has different packages. No conflicts.
Creating and activating
Python's built-in venv module creates virtual environments:
python -m venv venvThis creates a venv/ directory with a fresh Python installation. The directory name venv is a convention — you can name it anything, but most projects use venv or .venv.
Activate the environment to start using it:
source venv/bin/activateYour terminal prompt changes to show (venv), confirming the environment is active. Now pip install writes to this environment only.
To deactivate and return to the global Python:
deactivateOne rule to follow
Always create a virtual environment before installing packages for a project. This habit prevents dependency conflicts and keeps your global Python clean.
Instructions
Create and activate a virtual environment.
- Create a virtual environment named
venvusing Python'svenvmodule. - Activate the virtual environment.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding