I inherited a Django project in 2019 that wouldn't run on my machine because the previous developer had installed everything globally. My system Python had Django 2.2 for another client project, but this codebase needed Django 3.0 and an older version of Pillow that conflicted with my other work. I spent an afternoon uninstalling and reinstalling packages before I realized the real problem wasn't the packages — it was the lack of isolation. That was the last time I worked without a virtual environment. If you are writing any Python beyond a one-off script, virtual environments are not optional tooling. They are how you keep projects reproducible, portable, and sane.
The Dependency Collision That Breaks Projects Without Isolation
When you install a Python package with pip without an environment, it goes into your global site-packages directory. Every project on your machine then shares that single set of installed libraries. In my experience, this works until it suddenly doesn't — and when it fails, it fails in confusing ways.
Consider a simple scenario. Project A requires requests==2.28.0 and Project B requires requests==2.31.0 because of a security fix. With a global install you can only have one version at a time. Upgrading for Project B silently breaks Project A, and pip won't warn you that you've just introduced a regression. This gets worse with transitive dependencies. You might install black for formatting and it pulls in click==8.1.7, but your CLI tool pinned click==7.1.2 and now its tests start throwing TypeError on argument parsing.
System Python adds another layer of risk. On macOS and many Linux distributions, the OS itself relies on Python for system utilities. Installing or upgrading packages globally can overwrite libraries the OS expects, which can lead to broken package managers or even login scripts that stop working. I've seen developers break their apt-installed Python on Ubuntu by running sudo pip install, which is a painful recovery.
A virtual environment solves this by creating a self-contained directory with its own Python interpreter, its own pip, and its own lib/pythonX.Y/site-packages. Nothing you install inside it leaks out, and nothing outside it leaks in unless you explicitly allow it. Each project gets its own dependency graph, which means you can work on five projects with five conflicting requirement sets on the same machine without ever thinking about it.
What isolation actually protects you from
Isolation doesn't just prevent version collisions. It also makes your builds deterministic. When you hand your project to a teammate or deploy it to CI, you can be confident that pip install -r requirements.txt inside a fresh environment will reproduce exactly what you had locally. It protects you from the "works on my machine" problem because your machine stops being special — every machine creates the same isolated environment from the same manifest. This is also why pairing virtual environments with proper packaging, as described in Modern Python Packaging with pyproject.toml and uv, makes collaboration so much smoother.
How venv Creates an Isolated Interpreter and Package Directory
The standard library module venv, available since Python 3.3, is the tool I recommend to every beginner and still use myself for most projects. According to the Python Documentation, venv creates a lightweight virtual environment with its own site directories, optionally isolated from system site packages.
When you run python -m venv .venv, Python does three things:
- Copies (or symlinks) the Python binary into
.venv/bin/python(or.venv\Scripts\python.exeon Windows). This binary is configured to look at the environment's directories first when resolving imports. - Creates a fresh
site-packagesdirectory at.venv/lib/python3.X/site-packages. This directory starts empty except forpip,setuptools, andwheel. Your global packages are not visible unless you create the environment with--system-site-packages, which I almost never recommend. - Installs activation scripts for different shells (
activate,activate.csh,activate.fish,Activate.ps1) that adjust yourPATHand prompt. Activation doesn't move files; it just prepends the environment'sbindirectory to yourPATHso that typingpythonorpipresolves to the environment's versions.
An important detail that trips up newcomers: a virtual environment does not copy the entire standard library. It reuses it from the base installation. That keeps environments small — typically 20-30 MB initially — and fast to create. What it does isolate completely is third-party packages and the pip executable itself.
Where the environment lives on disk
I've found that keeping the environment inside the project root as .venv or venv is the most practical pattern. It makes the project self-contained, it is automatically ignored if you add .venv/ to .gitignore, and tools like VS Code, PyCharm, and pip detect it without extra configuration. Some developers prefer a central location like ~/.virtualenvs (the virtualenvwrapper pattern). That works, but I've had fewer path-related surprises by keeping the environment next to the code it serves, especially when using Docker or when a project needs multiple environments for different Python versions.
Creating and Activating a venv Across Windows, macOS, and Linux
The commands are almost identical across platforms, but the activation step differs. Here is the workflow I use daily.
First, confirm which Python you are using. On systems with both Python 2 and 3 you should be explicit:
python3 --version
# Python 3.11.6
which python3
# /usr/local/bin/python3 or /opt/homebrew/bin/python3
Create the environment. I always name it .venv so it stays hidden and consistent across projects:
# Create the environment in the project root
python3 -m venv .venv
# Verify what was created
ls -la .venv
# bin/ include/ lib/ pyvenv.cfg
cat .venv/pyvenv.cfg
# home = /opt/homebrew/bin
# include-system-site-packages = false
# version = 3.11.6
The pyvenv.cfg file is worth inspecting. It records which base Python was used to create the environment and whether system site-packages are included. If you upgrade your system Python to 3.12, your old .venv will still point at 3.11 — you need to recreate it to pick up the new interpreter.
Now activate it. This is the step where Windows diverges:
# macOS / Linux (bash, zsh)
source .venv/bin/activate
# Windows Command Prompt
.venv\Scripts\activate.bat
# Windows PowerShell (you may need to allow scripts)
.venv\Scripts\Activate.ps1
# fish shell
source .venv/bin/activate.fish
When activation succeeds, your shell prompt will show the environment name, like (.venv) user@host:~/myproject$. You can also verify without looking at the prompt:
which python
# /Users/you/myproject/.venv/bin/python
which pip
# /Users/you/myproject/.venv/bin/pip
python -c "import sys; print(sys.prefix)"
# /Users/you/myproject/.venv
To leave the environment, just run deactivate. That restores your original PATH. Nothing is deleted — deactivation only undoes the shell changes. I often keep two terminal tabs open with different environments activated to compare behavior across projects.
Common activation pitfalls I've run into
On macOS with Homebrew, if you see command not found: python after activation, it usually means the environment was created with python instead of python3 and your shell doesn't have a python shim. Recreate with python3 -m venv .venv. On Windows PowerShell, execution policy will block Activate.ps1 by default. Run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser once, then activation works. And if you use VS Code, select the interpreter explicitly with Cmd+Shift+P > Python: Select Interpreter — relying on auto-detection alone sometimes picks the global interpreter after a restart.
Managing Dependencies with pip Inside an Active Environment
Once the environment is active, pip operates exclusively inside it. This is where the isolation pays off. You can install, upgrade, and remove packages without affecting any other project.
Here is a typical cycle for a new web project:
# Make sure pip itself is current inside the env
python -m pip install --upgrade pip
# Install what you need
pip install django==4.2.7 requests==2.31.0 pytest
# Check what is actually installed and where it came from
pip list
pip show django
# Freeze exact versions for reproduction
pip freeze > requirements.txt
cat requirements.txt
# asgiref==3.7.2
# Django==4.2.7
# requests==2.31.0
# ...
That requirements.txt file is your environment's manifest. Anyone cloning the repo can recreate your environment with pip install -r requirements.txt after creating their own .venv. In my experience, committing requirements.txt (or a requirements/ directory with base.txt, dev.txt, etc.) is non-negotiable for reproducible builds.
For a more modern approach, define dependencies in pyproject.toml under [project.dependencies] and install the project in editable mode with pip install -e .. This keeps metadata, dependencies, and build configuration in one place. If you are moving toward that setup, the guide on Modern Python Packaging with pyproject.toml and uv walks through the structure I now use by default.
Keeping pip and dependencies healthy
A few habits have saved me hours of debugging. First, always upgrade pip right after creating an environment — older pip versions sometimes resolve dependencies differently and miss wheels, falling back to slow source builds. Second, use pip install --dry-run (pip 22.2+) to preview what an install will change before you commit to it. Third, avoid sudo pip install entirely; if you feel tempted to use sudo, it means your environment isn't activated. Finally, regenerate your freeze file after every intentional change. I keep a make freeze target that runs pip freeze > requirements.txt so the file never drifts from the actual environment. When you pair this discipline with good tests, you get the kind of confidence described in Pytest Patterns That Scale: Fixtures, Mocks and Parametrize — your test suite runs against a known, isolated set of packages rather than whatever happened to be installed globally.
venv vs virtualenv vs Conda: Which Isolation Tool Fits Your Project
Beginners often ask whether they should use venv, virtualenv, or Conda. They all solve isolation, but they make different trade-offs. I've used all three extensively, and here is how I think about the choice.
| Feature | venv (stdlib) | virtualenv | Conda / Mamba / Miniconda |
|---|---|---|---|
| Installation required | None — included with Python 3.3+ | pip install virtualenv |
Separate installer (Anaconda/Miniconda/Mambaforge) |
| Python versions | Uses the Python you created it with; one version per env | Can create envs for different Python versions if they are installed | Can install and manage multiple Python versions itself |
| Non-Python deps | No — Python packages only | No — Python packages only | Yes — handles C libraries, R, CUDA, etc. |
| Speed of creation | Very fast (1-2 seconds) | Fast, slightly slower due to seeding mechanisms | Slower; solves full SAT environment |
| Best for | Standard Python web apps, scripts, libraries | Legacy support (Python 2), faster seeding, extra features | Data science, scientific computing, GPU stacks |
| Activation model | Shell activation scripts | Shell activation scripts (compatible) | conda activate envname with shell integration |
For pure Python projects — APIs, Django/Flask apps, automation scripts, libraries — venv is sufficient and has the advantage of being built-in. No extra tool to install, no new package manager to learn, and every Python developer will understand your setup. I default to it.
virtualenv was essential before venv existed and it still offers a few extras: it is faster at seeding environments via wheels, it supports Python 2.7 if you still maintain legacy code, and it has a richer discovery mechanism for finding Python interpreters. If you are already comfortable with venv, you don't need to switch unless you hit one of those specific needs.
Conda is a different beast. It is not just a Python environment manager but a cross-language package manager. If your project depends on numpy linked against MKL, gdal, pytorch with CUDA, or R libraries, Conda's ability to resolve and install non-Python binaries is valuable. The downside is complexity and size — Conda environments are heavier, dependency solving can be slow, and you now have a second package manager to reconcile with pip. For most web development work, I've found that burden unnecessary.
Newer tools like uv, pipx, and poetry build on top of these foundations. uv in particular can create venv-compatible environments at remarkable speed and is worth evaluating if environment creation time matters in CI. But even then, the underlying isolation model is still the venv directory structure.
Keeping Virtual Environments Healthy in Long-Lived Codebases
Creating an environment is easy; maintaining it over months is where discipline matters. I've seen repositories where the .venv was created once and never recreated, accumulating stale packages and workarounds that no one could reproduce on a fresh machine.
First, never commit the environment directory. Add .venv/, venv/, and __pycache__/ to .gitignore on day one. The environment is a build artifact, not source. What you commit is the recipe — requirements.txt, pyproject.toml, or poetry.lock — not the cooked meal. A teammate should be able to run two commands (python -m venv .venv && pip install -r requirements.txt) and get what you have.
Second, recreate environments periodically. In my experience, a monthly recreation catches drift early. Dependencies release patches, wheels change, and a package that installed fine three months ago might now require a newer setuptools. I have a personal rule: if I'm about to cut a release or onboard someone, I delete and rebuild the environment from scratch first. It takes 30 seconds and confirms that my manifest is complete.
# Recreate cleanly
deactivate
rm -rf .venv
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
pip install -r requirements.txt
pytest -q
# If tests pass here, the manifest is good
Third, separate development dependencies from production ones. A pattern I use in every project is:
# requirements.txt (production)
Django==4.2.7
gunicorn==21.2.0
psycopg2-binary==2.9.9
# requirements-dev.txt (development)
-r requirements.txt
pytest==7.4.3
black==23.10.1
mypy==1.7.0
ruff==0.1.6
Production installs only what it needs, which keeps images small and attack surface narrow. For static analysis with mypy, having a clean dev environment ensures your type checking is consistent, and that connects directly to practices in Python Type Hints: A Practical Guide for Production Code — type hints are far more valuable when the checker runs in a reproducible environment with pinned versions.
Dealing with multiple Python versions
If you maintain libraries that support 3.9 through 3.12, keep a separate environment per version. Tools like pyenv let you install multiple interpreters, and you can then create .venv39, .venv312, etc., or use tox / nox to automate it. I've found that testing against at least the lowest and highest supported versions in isolated environments catches compatibility issues — like the datetime.UTC addition in 3.11 or the asyncio.TaskGroup changes — before users do.
Finally, document the workflow. A short section in your README.md that shows how to create the environment, activate it, and install dependencies reduces friction for new contributors to near zero. The best project setup is one where a new developer can go from git clone to passing tests in under two minutes without asking questions.
Frequently Asked Questions
Should I check my .venv folder into version control?
No. Your virtual environment contains binaries, compiled extensions, and thousands of files specific to your OS and Python version. It can be several hundred megabytes and will not work on another machine. Instead, commit your dependency manifest — requirements.txt, pyproject.toml, or poetry.lock — and add .venv/ to .gitignore. Anyone cloning the project recreates the environment with one or two commands.
Do I need to activate the environment every time I work on the project?
Yes, for each new terminal session. Activation sets your PATH so that python and pip refer to the environment's copies. Some editors like VS Code activate it automatically for their integrated terminal once you select the interpreter, but for standalone terminals you need to run source .venv/bin/activate (or the Windows equivalent). If you forget, which python will show the global interpreter instead of the .venv path.
What is the difference between venv and virtualenv?
venv is the standard library module included with Python 3.3 and later. virtualenv is a third-party tool that predates venv and still provides extra features like support for Python 2.7, faster environment creation via wheel seeding, and broader interpreter discovery. For most modern Python 3 projects, venv does everything you need and requires no installation. Use virtualenv only if you need one of its specific additional capabilities.
Can I use a virtual environment with Jupyter notebooks?
Yes. Create and activate your environment, install ipykernel inside it with pip install ipykernel, then register the environment as a kernel with python -m ipykernel install --user --name=myproject --display-name="Python (myproject)". The notebook server will then let you select that kernel from the Kernel > Change Kernel menu. This ensures your notebooks import exactly the packages pinned in your environment rather than the system or Conda base environment.