Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

Python virtual environments: isolate your projects

By updated

Improve this page

Logo Python

You are working on two Python projects: one uses Django 3.2, the other Django 4.2. Without isolation, installing the new version would overwrite the old one and break your first project. Virtual environments solve this problem by creating an isolated space for each project, with its own package versions.

A virtual environment is a directory containing a link to the Python interpreter and a dedicated space for packages. On Linux and macOS, venv creates symbolic links to the interpreter by default, not a copy (the --copies option forces a copy). If Python is updated on the system, the environment may therefore stop working: you then recreate it. Once you activate it, every pip install command affects only that environment: your system stays intact, and so do your other projects.

This guide shows you how to create, use and manage virtual environments with venv (the tool built into Python), then explores alternatives such as pipenv and uv.

What you will learn

This guide covers the whole life cycle of Python virtual environments. Each section comes with commands you can run right away.

By the end of this guide, you will be able to:

  • Understand the problem of dependency conflicts and why isolation is needed
  • Create a virtual environment with venv in a single command
  • Activate and deactivate the environment depending on your operating system
  • Install packages in isolation with pip
  • Manage dependencies with requirements.txt for reproducible environments
  • Choose the right alternative among venv, virtualenv, pipenv and uv

Why use a virtual environment?

The dependency conflict problem

Without a virtual environment, all your Python projects share the same globally installed packages. Here is what can go wrong:

SituationProblemConsequence
Project A uses requests==2.25Project B needs requests==2.31One of the two projects breaks
You test a new version of FlaskThe old project is no longer compatibleRegression in production
You collaborate with a colleagueTheir versions differ from yours"It works on my machine"
You deploy to productionThe server has other versionsUnpredictable errors
Without a virtual environment, projects A, B and C share the global Python: Django 3.2 is overwritten by 4.2, requests 2.25 by 2.31, and Flask 1.x conflicts; project A no longer works.Global Python: shared packagesProject Aneeds Django 3.2Project Bneeds Django 4.2Project Cneeds Flask 1.xDjango 3.2overwritten by 4.2requests 2.25overwritten by 2.31Flask 1.xconflictno longer worksoverwrites Django 3.2conflicts with others
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The solution: isolation

With a virtual environment, each project has its own space:

With virtual environments, each project has its own .venv directory: Django 3.2 and Python 3.9 for A, Django 4.2 and Python 3.11 for B, Flask 2.3, SQLAlchemy 2.0 and Python 3.10 for C, with no conflict.Project AProject BProject C.venv/.venv/.venv/Django==3.2requests==2.25Python 3.9Django==4.2requests==2.31Python 3.11Flask==2.3SQLAlchemy==2.0Python 3.10
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The Django, Flask and Python versions in the diagram are examples of existing projects. To follow this guide, you need Python 3.11 or newer.

Concrete benefits:

  • No conflicts, each project has its own package versions
  • Reproducibility, export requirements.txt and recreate the identical environment elsewhere
  • Safety, testing a new version cannot break other projects
  • Cleanliness, delete a project = delete its environment, nothing is left behind

Create a virtual environment with venv

The venv module has been built into Python since version 3.3, and there is nothing to install with the Python from python.org or the one on most other systems.

Step 1: Check Python

Before you start, check that Python 3.11 or later is installed:

Terminal window
python3 --version

Expected output: Python 3.11.6 (or a later version)

Step 2: Create the environment

In your project directory, run:

Terminal window
python3 -m venv .venv

This command creates a .venv directory containing:

Directory/FileContents
bin/ (Linux/macOS) or Scripts/ (Windows)Python executables and activation scripts
lib/Packages installed in this environment
include/Header files for C extensions
pyvenv.cfgEnvironment configuration

Step 3: Check the creation

List the contents of the directory you just created:

Terminal window
ls -la .venv/

You should see the bin/, lib/, include/ directories and the pyvenv.cfg file. With Python 3.13, venv also adds a lib64 link that points to lib and a .gitignore file.

Activate the virtual environment

Creating the environment does not activate it automatically. Activation changes your terminal so that it uses the environment's Python instead of the global Python.

Activation commands by system

Terminal window
source .venv/bin/activate

Alternative with a dot:

Terminal window
. .venv/bin/activate

How do you know whether the environment is active?

After activation, your prompt changes to show the name of the environment:

Terminal window
# Before activation
user@machine:~/my-project$
# After activation
(.venv) user@machine:~/my-project$

Additional check: the which python command (Linux/macOS) or where python (Windows) must point to .venv/bin/python:

/home/user/my-project/.venv/bin/python
which python

Deactivate the environment

When you have finished working on the project:

Terminal window
deactivate

The prompt goes back to normal and the python and pip commands use the global installation again.

Install packages with pip

Once the environment is active, pip installs packages only in that environment.

Install a package

Terminal window
pip install requests

This command:

  1. Downloads the requests package from PyPI
  2. Installs it in .venv/lib/python3.x/site-packages/
  3. Automatically installs its dependencies (urllib3, certifi, etc.)

Install a specific version

To guarantee compatibility, specify an exact version:

Terminal window
pip install requests==2.31.0

The number 2.31.0 illustrates the syntax. This version is old: vulnerabilities have been published since and fixed in the 2.32 branch. On a real project, choose the current version, after checking it.

Available version syntaxes:

SyntaxMeaning
requests==2.31.0Exact version
requests>=2.28.0Minimum version
requests>=2.28,<3.0Version range
requests~=2.31.0Compatible with 2.31.x

List installed packages

Terminal window
pip list

Output of this form, versions vary:

Package Version
------------------ ---------
certifi 2023.11.17
charset-normalizer 3.3.2
idna 3.6
pip 23.3.1
requests 2.31.0
urllib3 2.1.0

Update a package

Updating a package installs the latest version available on PyPI that is compatible with your Python version, without asking for confirmation. It also touches transitive dependencies if the new version requires others. On a project whose requirements.txt is versioned, regenerate that file right afterwards, otherwise your local environment and your colleagues' silently diverge.

Terminal window
pip install --upgrade requests

Uninstall a package

Terminal window
pip uninstall requests

Confirm with y when asked.

Manage dependencies with requirements.txt

The requirements.txt file lists all the dependencies of your project. It lets you recreate an identical environment on another machine.

Export the current dependencies

Terminal window
pip freeze > requirements.txt

Generated content:

certifi==2023.11.17
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.1.0

Install from requirements.txt

On a new machine or after cloning a project:

  1. Create a virtual environment

    Terminal window
    python3 -m venv .venv
  2. Activate the environment

    Terminal window
    source .venv/bin/activate
  3. Install the dependencies

    Terminal window
    pip install -r requirements.txt

All the dependencies are installed with the exact versions specified.

Best practices for requirements.txt

1. Separate direct from indirect dependencies

Create two files:

  • requirements.in, packages you use directly
  • requirements.txt, generated from the previous one by pip-compile (a pip-tools tool), includes the transitive dependencies with their exact versions

2. Version requirements.txt in Git

Terminal window
git add requirements.txt
git commit -m "Add project dependencies"

3. Keep versions up to date

Periodically, check for security updates:

Terminal window
pip list --outdated

Remove a virtual environment

A virtual environment is a simple directory. To remove it:

Terminal window
rm -rf .venv

Structure of a typical Python project

Here is how to organize a Python project with a virtual environment:

my-project/
├── .venv/ # Virtual environment (excluded from Git)
├── .gitignore # Includes .venv/
├── requirements.txt # Dependencies
├── src/ # Source code
│ ├── __init__.py
│ └── main.py
├── tests/ # Tests
│ └── test_main.py
└── README.md

Minimal contents of .gitignore:

# Virtual environment
.venv/
venv/
env/
# Python cache
__pycache__/
*.pyc
*.pyo
# pip
pip-log.txt

Alternatives to venv

venv suits most projects, but other tools offer extra features.

Tool comparison

Read this table by the Use case column rather than by the strengths: these tools do not replace one another, they answer different constraints. The conda row stands apart, as it is the only one in the list that also installs non-Python system libraries (BLAS, CUDA, GDAL), which pip cannot do. The other four are limited to Python packages and differ mainly in installation speed and in the format used to lock versions.

ToolStrengthsUse case
venvBuilt into Python, simpleStandard projects
virtualenvFaster creation, advanced optionsCI/CD, multi-interpreter projects
pipenvPipfile.lock, integrated managementTeams, reproducibility
uvUltra-fast (Rust), pip-compatibleModern projects, CI/CD
condaNon-Python packages, data scienceML, scientific computing

virtualenv

Older than venv, of which it is the direct ancestor, virtualenv creates environments faster because it bundles a copy of pip instead of rebuilding it each time. Beware of a persistent misconception: virtualenv no longer creates Python 2 environments since version 20.22.0 of April 2023, and since 21.5.0 of June 2026 it requires a Python 3.9 or later interpreter, both to run and as the target. If you still need to serve Python 2, you need an old, frozen version of virtualenv.

Terminal window
pip install virtualenv
virtualenv .venv
source .venv/bin/activate

pipenv

Combines a virtual environment and dependency management in a single tool. Uses Pipfile instead of requirements.txt.

Terminal window
pip install pipenv
pipenv install requests # Creates the env and installs the package
pipenv shell # Activates the environment

Generated files:

  • Pipfile, readable dependencies
  • Pipfile.lock, exact locked versions

A modern tool written in Rust, announced by its publisher Astral as 10 to 100 times faster than pip for installing packages (the publisher's figure, published on the project repository: measure it on your own installations). The installation below, written for Linux x86_64, fetches the binary archive published on GitHub and the associated checksum file, then refuses to continue if the two do not match. The sha256sum --check command must answer OK; any other answer means the archive was altered or truncated, so do not extract anything in that case.

Terminal window
# Install uv from a verified archive (version 0.13.8, published on 2026-11-12)
UV_VERSION=0.13.8
BASE="https://github.com/astral-sh/uv/releases/download/${UV_VERSION}"
curl -sSLO "${BASE}/uv-x86_64-unknown-linux-gnu.tar.gz"
curl -sSLO "${BASE}/uv-x86_64-unknown-linux-gnu.tar.gz.sha256"
sha256sum --check uv-x86_64-unknown-linux-gnu.tar.gz.sha256
tar -xzf uv-x86_64-unknown-linux-gnu.tar.gz
mkdir -p ~/.local/bin
install -m 0755 uv-x86_64-unknown-linux-gnu/uv ~/.local/bin/uv
# Create an environment and install packages
uv venv
source .venv/bin/activate
uv pip install requests

Benefits of uv:

  • Compatible with requirements.txt and pyproject.toml
  • Deterministic dependency resolution
  • Global cache shared between projects

pipx: install global CLI tools

Some Python tools are global CLIs (black, flake8, httpie...) that you want to use everywhere, not in one specific project.

Problem: installing them globally with pip can create conflicts.

Solution: pipx installs each tool in its own isolated environment, while making the command available globally.

One installation detail catches readers out on Debian 12+, Ubuntu 23.04+ and recent Fedora: these distributions mark their system Python as externally managed (file /usr/lib/python3.X/EXTERNALLY-MANAGED, defined by PEP 668), and pip install outside a virtual environment fails there with error: externally-managed-environment (observed on Debian 13 with Python 3.13.5 and pip 25.1.1). So go through the distribution package.

Terminal window
# Install pipx (recent Debian / Ubuntu: the system package is the official way)
sudo apt install pipx
# Elsewhere, or if the package does not exist:
# python3 -m pip install --user pipx
pipx ensurepath
# Install isolated global tools
pipx install black
pipx install httpie
pipx install poetry
# Use the tool anywhere
black --version
http https://api.github.com

Troubleshooting

The environment does not activate

The activation script only changes variables of the current shell, including PATH and VIRTUAL_ENV. Launched as a program (./activate instead of source), it runs in a subshell that disappears immediately: no error, no effect. So check how you call the script before suspecting the environment itself. The last row of the table matches this case.

SymptomLikely causeFix
source: not foundIncompatible shellUse bash or . .venv/bin/activate
PowerShell errorExecution policySet-ExecutionPolicy RemoteSigned -Scope CurrentUser
Prompt does not changeScript run without source, or .venv/bin/activate file missingUse source .venv/bin/activate; check that the file exists

pip installs globally despite activation

Two causes cover almost every case. The first is sudo: it replaces your PATH with the secure_path defined in /etc/sudoers. With the default configuration of most distributions, sudo pip install ignores the active environment and writes to the system packages.

The second is a moved or renamed environment. The .venv/bin/pip launcher is a script whose shebang (the first line, which designates the interpreter) contains the absolute path of the interpreter, fixed at creation. If you move the project directory, this path becomes invalid and you get cannot execute: required file not found. Recreate the environment then: it cannot be repaired. The check with the full path below tells the two situations apart without depending on PATH.

/path/to/.venv/bin/pip
# Check which pip is used
which pip
# If it does not, use it explicitly
.venv/bin/pip install requests

Version conflict during installation

pip install agrees to break an existing dependency: it prints an ERROR: pip's dependency resolver does not currently take into account all the packages that are installed line, then ends with Successfully installed and returns exit code 0. A CI pipeline that only looks at that code sees nothing. pip check rereads the metadata of the packages already present afterwards and reports unmet requirements. Run it after each series of installations: the output No broken requirements found. is the only acceptable result before freezing a requirements.txt.

Terminal window
# See conflicting dependencies
pip check
# Force the reinstallation of the dependencies
pip install --force-reinstall -r requirements.txt

The environment is corrupted

Sometimes, after a system Python update, the environment stops working:

Terminal window
# Solution: recreate the environment
rm -rf .venv
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Key takeaways

If you remember only six things from this guide, remember these:

  1. Always use a virtual environment, even for a small project.

  2. The .venv convention, name your environment .venv in the project directory. Since Python 3.13, venv excludes it from Git on its own with a .gitignore placed in the directory; before that, add .venv/ to the project's .gitignore.

  3. Activate before installing, check that (.venv) appears in your prompt before any pip install.

  4. requirements.txt for reproducibility, export with pip freeze > requirements.txt and version this file.

  5. deactivate to get out, simple but often forgotten. Your prompt goes back to normal.

  6. Deleting = deleting the directory, no complicated uninstall, just rm -rf .venv.

Knowledge check

Check that you have grasped the essentials of this guide. The questions cover only what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer

Checklist

Use this checklist to validate your mastery of virtual environments:

Basics

These four steps form the complete cycle of an environment. Do them in order in an empty directory: if which python still returns the system Python after activation, stop there, everything that follows in this guide would rest on an activation that did not take.

  • Create an environment with python3 -m venv .venv
  • Activate the environment (Linux/macOS/Windows)
  • Check the activation with which python
  • Deactivate with deactivate

Package management

The point that really makes the difference is the last one. Until you have replayed pip install -r requirements.txt in a new environment, you do not know whether your dependency file is complete; a package installed by hand and forgotten in the export only shows up when a colleague clones the project.

  • Install a package with pip install
  • Install a specific version
  • List installed packages with pip list
  • Export with pip freeze > requirements.txt
  • Install from pip install -r requirements.txt

Advanced

These four points are about project hygiene rather than how it works. The third is the one most often skipped: installing a command-line tool such as black or httpie with pip inside the project makes it unavailable elsewhere and adds it to requirements.txt although it is not part of the application's dependencies. pipx separates the two uses.

  • Remove an environment cleanly
  • Configure .gitignore correctly
  • Use pipx for global CLI tools
  • Know the alternatives (pipenv, uv)