Skip to content

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"
Activate

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ΒΆ

  1. 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
  1. 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)

  1. 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
Then run Python as usual (python, pytest, etc.). Exit with deactivate.