Beginner Python / Project Setup

Virtual Environments and Dependency Management

Set up isolated Python environments, manage dependencies properly, and avoid the "it works on my machine" problem.

2 min read Updated Feb 12, 2026 Reviewed Feb 10, 2026

Why Virtual Environments?

Every Python project has different dependencies — different packages, different versions. Without isolation, installing a package for one project can break another. Virtual environments solve this by creating isolated Python installations per project.

Creating Virtual Environments

Using venv (Built-in)

# Create
python -m venv .venv

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

# Activate (Windows)
.venvScriptsactivate

# Deactivate
deactivate

uv is a modern, extremely fast Python package manager written in Rust:

# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh

# Create venv + install
uv venv
uv pip install flask requests

# From requirements.txt
uv pip install -r requirements.txt

Managing Dependencies

requirements.txt

The traditional approach — a flat list of packages with pinned versions:

# Generate from current environment
pip freeze > requirements.txt

# Install from file
pip install -r requirements.txt

pyproject.toml (Modern Standard)

The modern approach consolidates project metadata and dependencies:

[project]
name = "my-project"
version = "1.0.0"
requires-python = ">=3.10"
dependencies = [
    "flask>=3.0",
    "requests>=2.31",
    "sqlalchemy>=2.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=8.0",
    "ruff>=0.3",
]

Common Patterns

Development vs Production Dependencies

Keep testing and development tools separate from production dependencies. Your production server does not need pytest or your linter.

.gitignore

Never commit your virtual environment to version control:

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

Troubleshooting

If you see “externally-managed-environment” errors on modern Linux/macOS, the system Python is protected. Always create a virtual environment first — never pip install into the system Python.

If packages seem missing after installation, make sure your virtual environment is activated. Check with which python — it should point to your .venv directory.

Summary

Virtual environments are not optional — they are foundational to professional Python development. Start every project by creating one. Your future self (and your teammates) will thank you.