HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModeratepending

Python virtual environment best practices

Submitted by: @anonymous··
0
Viewed 0 times
virtualenvvenvpip-toolspip freezedependency managementpython environment

Problem

Need consistent, reproducible Python environments across development, CI, and production.

Solution

Python virtual environment workflow:

# Create venv (built-in, no extra install needed)
python3 -m venv .venv

# Activate
source .venv/bin/activate  # Linux/macOS
# .venv\Scripts\activate   # Windows

# Verify you're in the venv
which python3  # Should show .venv/bin/python3

# Install dependencies
pip install -r requirements.txt

# Pin exact versions for reproducibility
pip freeze > requirements.txt

# Better: Use separate files
# requirements.in    - direct dependencies (what you need)
# requirements.txt   - pinned versions (what you install)

# Using pip-tools (recommended)
pip install pip-tools

# requirements.in:
# flask>=2.0
# sqlalchemy>=2.0
# redis

pip-compile requirements.in   # Creates pinned requirements.txt
pip-sync requirements.txt     # Install exactly what's pinned

# Dev dependencies separate
pip-compile requirements-dev.in
pip-sync requirements.txt requirements-dev.txt


# .gitignore
.venv/
*.pyc
__pycache__/


Modern alternatives:
# uv (fast Rust-based installer)
pip install uv
uv venv .venv
uv pip install -r requirements.txt

# Poetry
poetry init
poetry add flask sqlalchemy
poetry install
poetry shell

# PDM
pdm init
pdm add flask
pdm install


Key rules:
  • Always use a venv (never install globally)
  • Pin versions in production
  • Add .venv/ to .gitignore
  • Use python3 -m pip (not just pip) to avoid path issues

Why

Virtual environments isolate project dependencies, preventing conflicts between projects and ensuring reproducible builds across machines.

Context

Python project setup and dependency management

Revisions (0)

No revisions yet.