Python Virtual Environments
debt(d3/e3/b3/t5)
Closest to 'default linter catches the common case' (d3), modern pip warns about system-wide installs (PEP 668 externally-managed-environment) and tools like uv/pyenv make missing venvs obvious; not instant compile error but visible quickly.
Closest to 'simple parameterised fix' (e3), quick_fix is a small recipe: python -m venv .venv && activate && pip install -r requirements.txt — straightforward but more than one line.
Closest to 'localised tax' (b3), applies_to web/cli means the venv choice affects project setup and onboarding but doesn't reshape application architecture; it's a persistent but well-scoped commitment.
Closest to 'notable trap' (t5), the misconception that 'global pip install is fine for simple scripts' is the canonical beginner gotcha — common_mistakes show multiple documented pitfalls (committing .venv, forgetting to activate, version drift) that devs eventually learn.
Also Known As
TL;DR
Explanation
Virtual environments (venv, virtualenv) create a local copy of the Python interpreter with its own site-packages directory. Each project gets its own environment: pip install installs only there. Modern tools: venv (built-in, Python 3.3+), virtualenv (more features), pyenv (manages multiple Python versions), Poetry/PDM (virtualenv + dependency management + publishing). The equivalent of PHP Composer's vendor/ directory, but managed at the interpreter level.
Common Misconception
Why It Matters
Common Mistakes
- Committing the venv/ directory to version control — only requirements.txt or pyproject.toml should be committed.
- Not using pip freeze > requirements.txt or Poetry's lock file — recreating the environment reproduces different versions.
- Not activating the virtual environment before pip install — packages go to the global Python instead.
- Using different Python versions in development and production without pyenv — subtle compatibility bugs.
Code Examples
# Global pip install — pollutes system, causes conflicts:
pip install django==3.2 # Project A
pip install django==4.2 # Project B — overwrites Project A's version!
pip install requests==2.28 # Conflicts with system tools
# No isolation — projects interfere with each other
# Virtual environment per project:
python3 -m venv .venv # Create in project directory
source .venv/bin/activate # Activate (Unix)
# .venv\Scripts\activate # Activate (Windows)
pip install django==4.2 # Installs only in this venv
pip freeze > requirements.txt # Lock versions
# .gitignore:
.venv/
__pycache__/