Virtual environments
A virtual environment is a private Python install plus a private site-packages directory for one project. It keeps that project's dependencies from colliding with other projects or with the system interpreter.
Detailed Explanation
Global installs do not scale. Project A needs requests==2.28 and project B needs requests==2.32. One system site-packages cannot hold both. A virtual environment is a directory that contains a Python executable, a pip tied to it, and its own package tree. Activating the environment puts that executable first on PATH, so python and pip mean "this project".
python3 -m venv .venv is the standard library tool. It creates .venv/ with a copy or symlink of the interpreter. source .venv/bin/activate on Unix, or .venv\Scripts\activate on Windows, sets VIRTUAL_ENV and changes the prompt. You can skip activation and call .venv/bin/python directly; that is what IDEs and CI should do.
The environment is not the source tree. Do not commit .venv. Do commit the file that lists what belongs in it: requirements.txt, requirements.lock, or pyproject.toml plus a lock file. Recreate the environment on a new machine by creating a venv and installing from that file.
venv isolates packages, not Python versions. The environment is born from the interpreter you used to create it. To work on 3.11 and 3.12 you need both interpreters installed, then a venv from each. Tools such as uv, pyenv, and conda add version management on top. conda environments also manage non-Python binaries, which venv does not.
pip install without a venv writes into the interpreter's site-packages. On Linux that may be the system Python, and the OS package manager will fight you. On macOS a Homebrew Python is still shared by every project. Create a venv first, then install.
Deactivate with deactivate, or just leave the shell. Deleting the directory removes the environment. Nothing in the project source depends on the venv existing except local tooling.
Code Examples
import sys
from pathlib import Path
print(sys.prefix) # .../.venv when the env is active
print(sys.executable) # .../.venv/bin/python
print(Path(sys.prefix, "pyvenv.cfg").exists()) # True inside a venvpython3 -m venv .venv
.venv/bin/python -m pip install -U pip
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python -c "import sys; print(sys.prefix)"# CI and scripts should call the venv interpreter, not rely on activate.
.venv/bin/python -m pytestCommon Gotchas
Installing with the wrong `pip`
`pip` on `PATH` may belong to another interpreter. Use `python -m pip` after you have selected the venv's `python`.
Do not commit `.venv`
it is machine-specific and large. Commit the dependency list instead.
A venv is tied to one interpreter path
move the directory or upgrade the system Python and the venv can break. Recreate it.
`activate` is optional
`path/to/.venv/bin/python` is enough and is more reliable in cron, systemd, and CI.