Back to Python tutorials
Basic14 min read

Virtual Environments

Isolate project dependencies with venv, pip, and modern tools like uv or poetry.

Why Virtual Environments

Each project needs its own dependency versions. Global pip installs cause conflicts when Project A needs Django 4 and Project B needs Django 5.

Virtual environments create an isolated Python prefix with its own site-packages and scripts directory.

Commit requirements lockfiles, never the venv folder itself—add .venv to .gitignore.

  • Activate venv before running pip or pytest locally
  • Document Python version in .python-version or pyproject.toml
  • Recreate venv when upgrading major Python versions
python -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate
pip install -r requirements.txt

pip and Lockfiles

pip install package adds to environment. pip freeze > requirements.txt captures versions for reproducibility.

pip-tools compile generates pinned requirements.in outputs. Prefer pyproject.toml dependencies in modern projects.

Use pip install -e . for editable installs while developing libraries.

  • Pin transitive dependencies for production deploys
  • Audit with pip-audit or safety for CVEs
  • Separate dev dependencies in optional extras

Poetry and uv

Poetry manages pyproject.toml dependencies, virtualenv creation, and publishing in one CLI. Lock file poetry.lock ensures CI reproducibility.

uv is a fast Rust-based installer and resolver compatible with pip requirements and pyproject standards.

Choose one tool per repo; document setup in README so contributors align quickly.

  • Run poetry lock --no-update when changing pyproject constraints
  • Cache dependencies in CI for faster builds
  • Use python -m pip instead of bare pip when docs allow
uv venv
uv pip install -r requirements.txt
# or: poetry install

Get In Touch


Ready to discuss your next project? Drop me a message.