Explain it simply
Virtual environments in plain language
A virtual environment (venv) is a small private library of Python packages used by one project only. If project A needs Django 4.2 and project B needs Django 5.2, you cannot have both installed for the whole computer at once. With a venv per project, each version lives in its own folder and the two never collide.
Imagine two cooks sharing one kitchen. If one swaps the salt for sugar, the other's dish is ruined. A venv gives each cook a private spice drawer, while the stove itself, the Python interpreter, is still shared.
Problem → Why → Solution
The problem: global installs and the wrong interpreter
The day you run pip install --upgrade django globally for a new project, an older project that depends on Django 4.2 breaks at once. Even more confusing: the venv is activated in your terminal, but your code editor or a cron job uses the system Python, so the code works in the terminal and fails with ModuleNotFoundError from the editor's Run button.
pip install --upgrade django # global: every project now sees Django 5.x
python old_project/manage.py runserver
# ImportError in code written for Django 4.2
# a cron job / IDE calling /usr/bin/python3 instead of the project's interpreter
# ModuleNotFoundError: No module named 'requests'Why a venv and an interpreter check help
Each venv has its own site-packages folder, so upgrading in one project leaves the others alone. But the isolation only works when code runs on the right interpreter. That is why checking sys.executable, or calling the python inside .venv directly, is more reliable than trusting activation.
Core concept: what is inside a venv folder
python -m venv .venv creates a folder called .venv. Inside are three key parts: a pyvenv.cfg file that records where the base Python lives, a python executable in bin/ (Scripts\ on Windows) that links to or copies the base interpreter, and a private, empty site-packages folder. By default pip is installed into it as well, through ensurepip.
When the python inside .venv starts, it finds pyvenv.cfg in the folder above it, sets sys.prefix to the venv folder and looks for imports in that venv's site-packages. sys.base_prefix still points at the original installation. So sys.prefix != sys.base_prefix means you are running inside a venv. The standard library is still read from the base install, which is why a venv is small compared with a full Python installation.
| Command | What it does |
|---|---|
| python -m venv .venv | creates the folder, pyvenv.cfg, interpreter and pip |
| source .venv/bin/activate | macOS/Linux: puts .venv/bin first on PATH |
| .venv\Scripts\activate | the same on Windows (cmd or PowerShell) |
| deactivate | restores the original PATH and prompt |
Activation does nothing magical: it puts the venv's script folder at the front of the shell's PATH, sets the VIRTUAL_ENV variable and shows (.venv) in the prompt. Calling the interpreter by its full path, as in .venv/bin/python app.py, therefore works the same without activating, which is how cron jobs, Dockerfiles and systemd services do it. Scripts inside a venv contain absolute paths, so never move or copy the folder; delete it and create it again.
By default a venv cannot see the global site-packages, because pyvenv.cfg says include-system-site-packages = false. Creating it with the --system-site-packages option makes global packages visible too, but that throws away the main benefit of isolation, so avoid it unless you have a specific reason.
- python -m venv builds a folder
- pyvenv.cfg points to base Python
- .venv's python sets sys.prefix
- imports search venv site-packages
Isolation is decided by which python executable runs, not by whether the shell is activated.
General pattern
python -m venv <env-folder> # create once per project
source <env-folder>/bin/activate # macOS/Linux
<env-folder>\Scripts\activate # Windows
python -m pip install <package> # installs into the active env
python -m pip freeze > requirements.txt # record exact versions
deactivate # leave the envCreate one environment per project, activate it, install with python -m pip and record the versions in a file. Using python -m pip guarantees that pip belongs to the same python you are running.
Worked example: building and probing a venv from code
Instead of just showing the commands as text, this script uses the standard library's venv module to build a real venv in a temporary folder, then runs the interpreter inside it with subprocess and asks what it sees. It is the same as running python -m venv .venv --without-pip in a terminal.
Paths differ from machine to machine, so it prints only True/False values and a count. Creating the venv can take a few seconds.
import os
import subprocess
import tempfile
import venv
from pathlib import Path
# Same as running: python -m venv <folder> --without-pip
# (Windows can briefly lock python.exe, so cleanup errors are ignored.)
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
env_dir = Path(tmp) / ".venv"
venv.EnvBuilder(with_pip=False).create(env_dir)
print("pyvenv.cfg exists:", (env_dir / "pyvenv.cfg").exists())
scripts = "Scripts" if os.name == "nt" else "bin"
exe = "python.exe" if os.name == "nt" else "python"
env_python = env_dir / scripts / exe
print("own interpreter:", env_python.exists())
probe = (
"import sys, importlib.metadata as md\n"
"print('inside a venv:', sys.prefix != sys.base_prefix)\n"
"print('installed packages:', len(list(md.distributions())))"
)
result = subprocess.run([str(env_python), "-c", probe], cwd=tmp,
capture_output=True, text=True, check=True)
print(result.stdout.strip())Code breakdown
- Create the environment
venv.EnvBuilder(with_pip=False).create(env_dir)This is the class the python -m venv command uses underneath. with_pip=False skips installing pip, which is faster and leaves the environment with no packages at all.
- The marker file
print("pyvenv.cfg exists:", (env_dir / "pyvenv.cfg").exists())The presence of pyvenv.cfg is what makes the folder a venv. The interpreter looks for this file at startup to find the base Python.
- Scripts vs bin
scripts = "Scripts" if os.name == "nt" else "bin"Executables live in Scripts\ on Windows and in bin/ on macOS and Linux; the script picks the right one so it works on both.
- Ask the new interpreter
"print('inside a venv:', sys.prefix != sys.base_prefix)\n"Runs the venv's python as a child process and has it compare sys.prefix with sys.base_prefix. True proves that calling it by full path, with no activation, already puts you inside the venv.
- Nothing installed yet
"print('installed packages:', len(list(md.distributions())))"importlib.metadata lists the installed distributions the interpreter can see. 0 shows that whatever the parent process has installed, none of it leaks into the new venv.
pyvenv.cfg exists: True
own interpreter: True
inside a venv: True
installed packages: 0The everyday workflow
Follow these steps whenever you start a project or clone a teammate's repository. The name .venv is the most common choice, and most editors detect it automatically.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -c "import sys; print(sys.executable)" # confirm which python runs
echo ".venv/" >> .gitignore # the folder itself never goes into gitIf activation fails in PowerShell
If Windows PowerShell blocks scripts, Activate.ps1 fails with 'running scripts is disabled'. You can allow it for your user only with Set-ExecutionPolicy -Scope CurrentUser RemoteSigned, or skip activation and call .venv\Scripts\python.exe directly.
Editors such as VS Code and PyCharm need you to pick the interpreter inside .venv, through a setting like 'Python: Select Interpreter', so the Run button, debugger and test runner use the same interpreter as your terminal. A venv does not help you switch Python versions; each venv is tied to the Python version that created it.
In real projects
Virtual environments in real projects
Almost every professional Python project has a .venv folder and a dependency file. A new developer should be able to clone and get a working environment in three commands, and the CI server builds a brand-new environment from scratch on every build before running the tests. Always rebuilding from scratch catches the 'works on my machine' problem.
- Deployment: servers call /srv/app/.venv/bin/python, or gunicorn, by full path instead of relying on activation.
- Docker: a container is already isolated, yet multi-stage builds often create a venv in one stage and copy it into the final image, keeping the same path inside the image.
- Tools: uv, Poetry and pipenv create and manage the venv for you, but underneath they use the same venv layout this lesson describes.
Common mistakes
Common mistakes with virtual environments
Committing or moving the .venv folder
.venv contains absolute paths from your machine and files compiled for one OS, so it does not work elsewhere, and it bloats the repository by many megabytes. Put it in .gitignore and commit requirements.txt instead. After renaming or moving the project folder, delete the venv and create it again.
pip and python pointing at different interpreters
On a machine with several Pythons, pip install requests may install into one Python while python app.py runs on another, so you get ModuleNotFoundError right after 'installing'. Always use python -m pip, and print sys.executable when in doubt.
Assuming editors and cron know about your activation
Activation changes the PATH of that one shell window only. Editors, cron and Windows Task Scheduler start with their own environment and may use the global Python. Select the interpreter in the editor, and write the full path to the .venv python in scheduled jobs.
Mini challenge
Mini challenge: an environment report
Write three functions: one that parses the text of a pyvenv.cfg file into a dict, one that builds the venv interpreter path for each OS, and one that checks whether the current script runs inside a venv. Try them on a sample pyvenv.cfg and print a report.
- parse_pyvenv_cfg(text) turns 'key = value' lines into a dict, stripping spaces
- Report 'isolated' when include-system-site-packages is "false"
- interpreter_path(env_dir, windows) returns Scripts\python.exe on Windows and bin/python elsewhere
- in_virtualenv() compares sys.prefix with sys.base_prefix
import sys
from pathlib import PurePosixPath, PureWindowsPath
SAMPLE_CFG = """\
home = /usr/local/bin
include-system-site-packages = false
version = 3.13.1
"""
def parse_pyvenv_cfg(text):
# TODO: split each "key = value" line once on "=" and strip both sides
...
def interpreter_path(env_dir, windows):
# TODO: Scripts/python.exe on Windows, bin/python elsewhere
...
def in_virtualenv():
# TODO: compare sys.prefix with sys.base_prefix
...
# TODO: print the version, whether the env is isolated, both interpreter
# paths for ".venv", and whether this script runs inside a venvExpected: It prints 'created from Python 3.13.1', 'isolated from global packages: True', .venv\Scripts\python.exe and .venv/bin/python. The last line is True inside a venv and False outside one.
Show hint
line.split("=", 1) splits only at the first =, so a value containing = survives. PureWindowsPath and PurePosixPath build each OS's path format without touching the file system, so the result is the same on any machine.
Show solution
import sys
from pathlib import PurePosixPath, PureWindowsPath
SAMPLE_CFG = """\
home = /usr/local/bin
include-system-site-packages = false
version = 3.13.1
"""
def parse_pyvenv_cfg(text):
settings = {}
for line in text.splitlines():
if "=" in line:
key, value = line.split("=", 1)
settings[key.strip()] = value.strip()
return settings
def interpreter_path(env_dir, windows):
if windows:
return PureWindowsPath(env_dir) / "Scripts" / "python.exe"
return PurePosixPath(env_dir) / "bin" / "python"
def in_virtualenv():
return sys.prefix != sys.base_prefix
cfg = parse_pyvenv_cfg(SAMPLE_CFG)
isolated = cfg.get("include-system-site-packages") == "false"
print("created from Python", cfg["version"])
print("isolated from global packages:", isolated)
print("Windows:", interpreter_path(".venv", windows=True))
print("macOS/Linux:", interpreter_path(".venv", windows=False))
print("this script runs in a venv:", in_virtualenv())Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A venv holds pyvenv.cfg, an interpreter and a private site-packages, keeping each project's packages apart.
- sys.prefix != sys.base_prefix means you are running inside a venv.
- Activation only changes PATH; calling the .venv python by full path does the same job.
- Use python -m pip, and check which interpreter editors and scheduled jobs use.
- Never commit .venv; after a move, recreate it and reinstall from requirements.txt.
Python Documentation — Virtual Environments and Packages — Python Software Foundation