Why Virtual Environments Matter
Python virtual environments solve a fundamental problem: different projects need different package versions. Without isolation, installing package A for one project can break package B in another. A virtual environment creates a self-contained directory with its own Python interpreter and installed packages.
Creating a Virtual Environment with venv
The venv module is built into Python 3.3+ and requires no installation:
# Create a virtual environment named 'venv'
python3 -m venv venv
# Activate it
source venv/bin/activate # Linux/macOS
venv\Scripts\activate # Windows PowerShell
# Verify it's active (shows path to venv python)
which python
# Install packages
pip install requests flask
# Save dependencies
pip freeze > requirements.txt
# Deactivate when done
deactivate
Recreating from requirements.txt
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
Using pyenv for Python Version Management
pyenv lets you switch between Python versions globally or per-project:
# Install pyenv (macOS)
brew install pyenv
# Install a Python version
pyenv install 3.12.0
# Set version for current directory
pyenv local 3.12.0
# Verify
python --version # Python 3.12.0
conda for Data Science Projects
conda manages both Python and non-Python dependencies (C libraries, CUDA, etc.):
# Create conda environment
conda create -n myproject python=3.11
# Activate
conda activate myproject
# Install packages
conda install numpy pandas scikit-learn
pip install anything-else
# Export environment
conda env export > environment.yml
# Recreate on another machine
conda env create -f environment.yml
When to Use Which Tool
- venv: Standard Python projects, web apps, scripting. Built-in, fast, lightweight.
- pyenv: Managing multiple Python versions on the same machine.
- conda: Data science, ML projects that require C/CUDA libraries. Slower but handles binary dependencies.
- uv: Modern replacement for pip+venv, 10-100x faster, drop-in compatible.
Frequently Asked Questions
Should I commit my venv directory?
No. Add venv/ to .gitignore. Commit requirements.txt or pyproject.toml instead.
Why does 'python' vs 'python3' matter?
On many Linux systems, python refers to Python 2 while python3 refers to Python 3. Inside an activated virtual environment, both point to the environment's interpreter.
How do I use a virtual environment in VS Code?
Press Ctrl+Shift+P → "Python: Select Interpreter" → choose the interpreter inside your venv folder.