Aller au contenu principal

06.3 - Virtual Environments, pip & Dependency Management

Theory 20 min Intermediate

Why Virtual Environments?

Without virtual environments, all projects share the same global Python installation — creating dependency conflicts:

Project A needs requests==2.28
Project B needs requests==2.31
→ CONFLICT!

A virtual environment gives each project its own isolated Python and packages.


Creating and Using venv

# Create
python3 -m venv venv

# Activate (macOS/Linux)
source venv/bin/activate

# Activate (Windows PowerShell)
venv\Scripts\Activate.ps1

# Prompt changes to show (venv)
(venv) $ pip install requests

# Deactivate
deactivate

Always add venv/ to .gitignore:

# .gitignore
venv/
__pycache__/
*.pyc
.env

pip — Package Management

# Install
pip install requests
pip install requests==2.31.0 # specific version
pip install "requests>=2.28" # minimum version

# Upgrade
pip install --upgrade requests

# Uninstall
pip uninstall requests

# List installed packages
pip list
pip list --outdated

# Show package info
pip show requests

# Search (deprecated — use pypi.org instead)

requirements.txt

# Generate from current environment
pip freeze > requirements.txt

# Install from requirements.txt
pip install -r requirements.txt

requirements.txt example:

requests==2.31.0
flask==3.0.0
pandas>=2.0.0
numpy>=1.24.0
python-dotenv==1.0.0

pip Best Practices

DevelopmentProduction
Filerequirements-dev.txtrequirements.txt
VersionsFlexible (>=)Pinned (==)
IncludesTesting, linting toolsRuntime only

uv — Modern Fast Package Manager

uv is a blazing-fast replacement for pip, developed by Astral:

# Install uv
pip install uv

# Create and manage virtual environments
uv venv
uv pip install requests

# Sync from requirements
uv pip sync requirements.txt

# Install with pyproject.toml
uv install

Key Vocabulary

TermDefinition
Virtual environmentIsolated Python installation per project
venvBuilt-in module to create virtual environments
pipPython package installer
requirements.txtFile listing project dependencies
pip freezeOutputs all installed packages with pinned versions
uvUltra-fast modern Python package manager
Dependency conflictTwo packages requiring incompatible versions of a shared dependency

Summary

  • Always create a virtual environment per project: python3 -m venv venv
  • Activate before installing anything: source venv/bin/activate
  • Use pip install package to install; pip freeze > requirements.txt to save
  • Add venv/ to .gitignore — never commit the virtual environment
  • Pin versions in production (==), use flexible versions in development (>=)
  • Consider uv for faster dependency management