venv β quick introΒΆ
What is a venv?ΒΆ
A virtual environment is a self-contained folder with its own Python interpreter and libraries. It keeps each projectβs dependencies isolated β so updating one project wonβt break another.
π Official docs
When to use itΒΆ
- Always if a project needs extra Python packages.
- Collaboration: teammates install the same dependencies in their own venv.
- Deployment: reproducible installs.
Basic usageΒΆ
1. Create and activateΒΆ
Windows (PowerShell)
python -m venv .venv
.\\.venv\\Scripts\\Activate.ps1
macOS / Linux (bash)
python3 -m venv .venv
source .venv/bin/activate
1.5 Create and Activaet (external)ΒΆ
macOS / Linux (bash)
Create
python3 -m venv "$HOME/.venvs/explainers"
source ~/.venvs/explainers/bin/activate
2. Upgrade pipΒΆ
python -m pip install -U pip
3. Install dependenciesΒΆ
Case A: pyproject.toml
[project]
dependencies = ["numpy", "requests"]
[project.optional-dependencies]
dev = ["pytest", "black"]
Install both runtime + dev tools:
python -m pip install -e ".[dev]"
π‘ ".[dev]" means: install this project (".") + optional dev dependencies ([dev]).
Case B: requirements.txt
python -m pip install -r requirements.txt
4. DeactivateΒΆ
deactivate
External venv in VS CodeΒΆ
- Create venv outside repo, e.g.
~/.venvs/example-app.
- Windows:
C:\Users\<you>\.venvs\example-app\Scripts\python.exe - macOS/Linux:
/home/<you>/.venvs/example-app/bin/python
- Point VS Code to it via
.vscode/settings.json:
{
"python.defaultInterpreterPath": "${env:USERPROFILE}\\.venvs\\example-app\\Scripts\\python.exe"
}
(on Windows)
{
"python.defaultInterpreterPath": "${env:HOME}/.venvs/example-app/bin/python"
}
(on macOS/Linux)
- Result: VS Code uses that interpreter for terminals, debugging, and Jupyter β without hardcoding usernames.
Daily workflowΒΆ
WindowsΒΆ
Inside repo venv
.\\.venv\\Scripts\\Activate.ps1
python -m pip install -e ".[dev]" # only once or when deps change
Using external venv
& $env:USERPROFILE\.venvs\example-app\Scripts\Activate.ps1
macOS / LinuxΒΆ
Inside repo venv
source .venv/bin/activate
python -m pip install -e ".[dev]" # only once or when deps change
Using external venv
source ~/.venvs/example-app/bin/activate
python, pytest, etc.).
Exit with deactivate.