28. Virtual Environments Deep Dive
Virtual environments isolate project dependencies. Without them, conflicting package versions break things. With them, each project gets its own clean Python environment.
The modern approach uses venv (built into Python 3.3+) or virtualenv (more mature, faster):
# Create a virtual environment
python -m venv myenv
# Activate it (Linux/macOS)
source myenv/bin/activate
# Activate it (Windows PowerShell)
myenv\Scripts\Activate.ps1
# Verify activation
which python # Should point to myenv/bin/python
python --version
# Install packages
pip install openai numpy pandas
# Freeze requirements
pip freeze > requirements.txt
# Deactivate when done
deactivate
The python -m venv approach is now Python's officially recommended method. Older tutorials may show pyenv, virtualenvwrapper, or other tools—these predate the venv module.
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Create a new virtual environment called test_env. Activate it, install numpy and requests, verify they're importable, create requirements.txt, then deactivate and delete the environment. Demonstrate you can recreate it from requirements.txt in a new location.