Python Virtual Environments
A virtual environment (venv) is a project-local Python installation. Each project gets its own packages — no version conflicts with the system Python or other projects.
Why bother
- Two projects can use different versions of the same library.
- You don't pollute the system Python (which the OS may rely on).
- "Works on my machine" becomes "works in the same venv on any machine".
Create and use
SHELL
# Create python -m venv .venv # Activate source .venv/bin/activate # macOS / Linux .venv\Scripts\activate # Windows PowerShell .venv\Scripts\activate.bat # Windows cmd # Now pip installs into the venv, not globally pip install -r requirements.txt # Done? leave it: deactivate
What changes when activated
pythonandpippoint at the venv's binaries.- Imports look in the venv's
site-packagesfirst. - Your shell prompt shows the venv name (usually).
The .venv folder
Don't commit it. Add to .gitignore:
.gitignore
.venv/ __pycache__/ *.pyc
Modern alternatives
| Tool | What it adds |
|---|---|
uv | Rust-fast installer + venv manager; near-instant. |
poetry / hatch / pdm | Project metadata + lock files + venvs. |
pipx | Each CLI app in its own venv. |
conda | Heavier; handles native libs too — common in science/ML. |
Tip: One venv per project. Don't share one across multiple repos — the moment two projects pin different versions of a library, you're stuck.
Example
Example
# Create + activate (run in shell, not code):
# python -m venv .venv
# source .venv/bin/activate # macOS / Linux
# .venv\\Scripts\\activate # Windows
# pip install -r requirements.txt
print('A venv keeps a project\'s deps isolated from the system Python.')
Try it Yourself »
Exercise
Create a virtual environment in .venv.
python -m
.venv
Four letters.
Discussion
Loading…