
Python virtual environments isolate project dependencies so different projects can use different package versions without conflict. In 2026, every Python project should use either venv, virtualenv, or the modern uv tool. This guide covers all three plus best practices.
📋 Table of Contents
Why Virtual Environments?
Without virtual environments, all packages install globally. Project A needs Django 4.2, Project B needs Django 5.0 — they cannot coexist globally. Virtual environments solve this by giving each project its own Python + packages.
venv (Built-In)
# Create virtual environment
python3 -m venv .venv
# Activate
source .venv/bin/activate # Linux/macOS
.venv\Scripts\activate # Windows PowerShell
# Install packages
pip install fastapi uvicorn sqlalchemy
# Save dependencies
pip freeze > requirements.txt
# Deactivate
deactivate
uv — The Fast Modern Tool (2026 Standard)
uv by Astral replaces pip, venv, and pyenv. It is 10-100x faster than pip because it is written in Rust. In 2026, uv is the recommended tool for new projects.
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create project with virtual env
uv init myproject
cd myproject
# Add dependencies (auto-creates .venv)
uv add fastapi uvicorn sqlalchemy
# Run script in venv
uv run python main.py
# Sync dependencies from pyproject.toml
uv sync
pyproject.toml vs requirements.txt
Modern Python projects use pyproject.toml instead of requirements.txt. It includes metadata, dependencies with version constraints, and tool configs.
[project]
name = "myapp"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"uvicorn>=0.30",
"sqlalchemy>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.4",
"mypy>=1.10",
]
Managing Multiple Python Versions
# uv can install Python versions too
uv python install 3.12 3.13
uv python list
# Pin Python version for project
uv python pin 3.12
# Or use pyenv for Python version management
pyenv install 3.12.3
pyenv local 3.12.3 # sets .python-version file
Best Practices
- Always name your venv
.venv— most editors auto-detect it - Add
.venv/to.gitignore - Commit
pyproject.tomlanduv.lockto version control - Use
uv syncon a new clone to reproduce exact dependencies - Separate dev dependencies from production dependencies
# .gitignore
.venv/
__pycache__/
*.pyc
.env
dist/
*.egg-info/
Conclusion
Virtual environments are non-negotiable for Python development. Use venv for simple projects, switch to uv for speed and modern dependency management. Your future self (and teammates) will thank you.
📚 You might also like
🔗 Share this article




✍️ Leave a Comment