iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

  • python and pip point at the venv's binaries.
  • Imports look in the venv's site-packages first.
  • Your shell prompt shows the venv name (usually).

The .venv folder

Don't commit it. Add to .gitignore:

.gitignore
.venv/
__pycache__/
*.pyc

Modern alternatives

ToolWhat it adds
uvRust-fast installer + venv manager; near-instant.
poetry / hatch / pdmProject metadata + lock files + venvs.
pipxEach CLI app in its own venv.
condaHeavier; 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

Test yourself

Q1. Create a venv with…
Q2. Activate on Linux/macOS with…
Q3. After activation, pip installs go…

Discussion

Loading…