Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 07 / Topic 7 of 9

Virtual environments (venv)

A virtual environment (venv) is a private folder of packages for one project. Think of it as a separate lunch box per project: nothing mixes. Project A can use requests 2.31 while project B uses requests 2.32, with no clash. Always make one per project.

Real-world example: start a new "weather app" project.

cd weather-app                # go into the project folder (cd = change folder, see Part 1)
python -m venv .venv          # create a venv in a folder named .venv

On macOS / Linux use python3 if python is not found. On Windows, py -m venv .venv also works.

Activate it, so python and pip now mean the venv's copies. Run this from the project folder:

System Command
Windows (Command Prompt) .venv\Scripts\activate.bat
Windows (PowerShell) .venv\Scripts\Activate.ps1
Windows (Git Bash) source .venv/Scripts/activate
macOS / Linux (bash, zsh) source .venv/bin/activate

Your prompt then starts with (.venv):

(.venv) $ python --version     # now uses the venv's Python
(.venv) $ deactivate           # leave the venv (same command on every system)
  • Add .venv/ to .gitignore. Never commit it. Share requirements.txt instead.
  • If PowerShell says "running scripts is disabled", run this once, then try again: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned.

๐Ÿ” Going deeper: a venv is just a folder with its own python, its own site-packages, and a small pyvenv.cfg text file. On macOS / Linux .venv/bin/python is a link to the real interpreter; on Windows .venv\Scripts\python.exe is a small copy (a redirector) that starts the real one. When that python starts, it finds pyvenv.cfg next to it (or one folder up), so it knows it is inside a venv: it sets sys.prefix to the venv folder and uses the venv's site-packages (check with import sys; print(sys.prefix)). "Activating" does not change Python at all. It only puts .venv/bin (Windows: .venv\Scripts) first on your PATH, sets the VIRTUAL_ENV environment variable, and adds (.venv) to your prompt. So you can skip activation and call .venv/bin/python (Windows: .venv\Scripts\python) directly, which is what editors and scripts usually do.

Read more: the official venv documentation.

Done here? The practice set for Part 7 โ€” 7 exercises with solutions โ€” is on the part page.

Search the guide