Python Virtual Environments
In this page:
Why Virtual Environments Matter
Different projects can need different versions of the same package; a virtual environment keeps each project's packages separate so they never conflict with each other.
Example: Why Virtual Environments Matter
Run after activating a venv, this installs Django 4.2 only inside that project's venv — a different project's venv can have Django 5.0 installed at the same time with no conflict.
pip install django==4.2
⚠️ Run this command in your terminal.
Creating a Virtual Environment
Running "python -m venv venv" creates a new folder named "venv" containing an isolated copy of Python and pip just for this project.
Example: Creating a Virtual Environment
Creates a new virtual environment folder named venv in the current directory.
python -m venv venv
⚠️ Run this command in your terminal.
Activating the Virtual Environment
On Linux or macOS you activate the environment with "source venv/bin/activate"; once active, your terminal prompt changes and any pip install goes into that environment only.
Note: Deactivate anytime with the "deactivate" command.
Example: Activating the Virtual Environment
Activates the virtual environment so installed packages stay isolated to this project.
source venv/bin/activate
⚠️ Run this command in your terminal.
Confirming the Active Environment
Running "which python" after activation shows the Python interpreter now points inside the venv folder, confirming the isolated environment is active.
Warning: On Windows the equivalent command is "where python".
Example: Confirming the Active Environment
Prints the path of the active Python interpreter to confirm the virtual environment is in use.
which python
⚠️ Run this command in your terminal.
- Installing project packages globally, causing conflicts between projects that need different versions.
- Forgetting to activate the virtual environment before installing packages.
- Committing the virtual environment folder itself into version control instead of ignoring it.
- A virtual environment isolates a project's Python packages from the rest of the system.
- The "venv" module (built into Python) creates virtual environments.
- You must activate a virtual environment before installing packages into it.
- Each project can have its own virtual environment with different package versions.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: